diff --git a/README.md b/README.md index 511bae11..ed54afdc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# polymer-cdn v2.3.1 +# polymer-cdn v2.6.0 **A mirror of Polymer's components so that they can be used directly from CDN** ![Polymer CDN is powered by MaxCDN](http://i.imgur.com/9obTXpk.png) @@ -10,7 +10,7 @@ ## How to use In general, given an element named `my-cool-element`, the CDN url for it will be: ``` -https://cdn.rawgit.com/download/polymer-cdn/2.3.1/lib/my-cool-element/my-cool-element.html +https://cdn.rawgit.com/download/polymer-cdn/2.6.0/lib/my-cool-element/my-cool-element.html ``` To be sure, browse this repo and copy-paste the url to the raw version into [RawGit](https://rawgit.com). @@ -49,7 +49,7 @@ which explains it in more detail. ## Contents -All the libraries available in polymer-cdn can be found side-by-side in the [lib](https://github.com/Download/polymer-cdn/tree/2.3.1/lib) subfolder. Contained therein are all elements [listed as compatible with Polymer 2](https://www.polymer-project.org/2.0/docs/about_20#elements). +All the libraries available in polymer-cdn can be found side-by-side in the [lib](https://github.com/Download/polymer-cdn/tree/2.6.0/lib) subfolder. Contained therein are all elements [listed as compatible with Polymer 2](https://www.polymer-project.org/2.0/docs/about_20#elements). > It looks like `gold-zip-input` wasn't actually ported to Polymer 2 yet at the time of writing this, despite being listed as compatible, as witnessed by incompatibility warnings concerning this element in the Bower output at the bottom of this page. Your mileage with this element may vary. @@ -64,383 +64,396 @@ These dependencies are themselves also listed at the top-level, so you can work tree for a library by carefully examining this diagram. ```sh -polymer-cdn#2.3.1 -├─┬ app-layout#2.0.4 -│ ├─┬ iron-flex-layout#2.0.1 -│ │ └─┬ polymer#2.3.1 -│ │ ├── shadycss#1.1.0 -│ │ └── webcomponentsjs#1.0.20 -│ ├─┬ iron-media-query#2.0.0 -│ │ └── polymer#2.3.1 -│ ├─┬ iron-resizable-behavior#2.0.1 -│ │ └── polymer#2.3.1 -│ ├─┬ iron-scroll-target-behavior#2.0.0 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 -├─┬ app-localize-behavior#2.0.0 +polymer-cdn#2.6.0 +├─┬ app-layout#2.1.0 +│ ├─┬ iron-flex-layout#2.0.3 +│ │ └─┬ polymer#2.6.0 +│ │ ├── shadycss#1.1.2 +│ │ └── webcomponentsjs#1.1.1 +│ ├─┬ iron-media-query#2.1.0 +│ │ └── polymer#2.6.0 +│ ├─┬ iron-resizable-behavior#2.1.0 +│ │ └── polymer#2.6.0 +│ ├─┬ iron-scroll-target-behavior#2.1.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├─┬ app-localize-behavior#2.0.1 │ ├── intl-messageformat#1.3.0 (latest is 2.2.0) -│ ├─┬ iron-ajax#2.0.6 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 +│ ├─┬ iron-ajax#2.1.3 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 ├─┬ app-pouchdb#2.1.1 -│ ├─┬ app-storage#2.0.2 -│ │ └── polymer#2.3.1 -│ ├── polymer#2.3.1 -│ ├── pouchdb#6.3.4 +│ ├─┬ app-storage#2.1.1 +│ │ └── polymer#2.6.0 +│ ├── polymer#2.6.0 +│ ├── pouchdb#6.4.3 │ └── pouchdb-find#0.10.5 -├─┬ app-route#2.0.3 -│ ├─┬ iron-location#2.0.2 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 -├── app-storage#2.0.2 -├─┬ gold-zip-input#2.0.0 -│ ├─┬ iron-form-element-behavior#2.0.0 -│ │ └── polymer#2.3.1 -│ ├─┬ iron-icon#2.0.1 -│ │ ├── iron-flex-layout#2.0.1 -│ │ ├─┬ iron-meta#2.0.3 -│ │ │ └── polymer#2.3.1 -│ │ └── polymer#2.3.1 -│ ├─┬ iron-validator-behavior#2.0.0 -│ │ ├── iron-meta#2.0.3 -│ │ └── polymer#2.3.1 -│ ├─┬ paper-input#2.0.5 -│ │ ├── iron-a11y-keys-behavior#2.0.1 -│ │ ├─┬ iron-autogrow-textarea#2.1.0 -│ │ │ ├─┬ iron-behaviors#2.0.0 -│ │ │ │ ├─┬ iron-a11y-keys-behavior#2.0.1 -│ │ │ │ │ └── polymer#2.3.1 -│ │ │ │ └── polymer#2.3.1 -│ │ │ ├── iron-flex-layout#2.0.1 -│ │ │ ├─┬ iron-validatable-behavior#2.0.0 -│ │ │ │ ├── iron-meta#2.0.3 -│ │ │ │ └── polymer#2.3.1 -│ │ │ └── polymer#2.3.1 -│ │ ├── iron-behaviors#2.0.0 -│ │ ├── iron-form-element-behavior#2.0.0 -│ │ ├─┬ iron-input#2.0.1 -│ │ │ ├─┬ iron-a11y-announcer#2.0.0 -│ │ │ │ └── polymer#2.3.1 -│ │ │ ├── iron-validatable-behavior#2.0.0 -│ │ │ └── polymer#2.3.1 -│ │ ├─┬ paper-styles#2.0.0 -│ │ │ ├── font-roboto#1.0.3 -│ │ │ ├── iron-flex-layout#2.0.1 -│ │ │ └── polymer#2.3.1 -│ │ └── polymer#2.3.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── iron-a11y-announcer#2.0.0 -├─┬ iron-a11y-keys#2.0.0 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ └── polymer#2.3.1 -├── iron-a11y-keys-behavior#2.0.1 -├── iron-ajax#2.0.6 -├── iron-autogrow-textarea#2.1.0 -├── iron-behaviors#2.0.0 -├─┬ iron-checked-element-behavior#2.0.0 -│ ├── iron-form-element-behavior#2.0.0 -│ ├── iron-validatable-behavior#2.0.0 -│ └── polymer#2.3.1 -├─┬ iron-collapse#2.0.0 -│ ├── iron-resizable-behavior#2.0.1 -│ └── polymer#2.3.1 +├─┬ app-route#2.1.0 +│ ├─┬ iron-location#2.2.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├── app-storage#2.1.1 +├─┬ gold-zip-input#2.1.0 +│ ├─┬ iron-form-element-behavior#2.1.1 +│ │ └── polymer#2.6.0 +│ ├─┬ iron-icon#2.1.0 +│ │ ├── iron-flex-layout#2.0.3 +│ │ ├─┬ iron-meta#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ ├─┬ iron-validator-behavior#2.1.0 +│ │ ├── iron-meta#2.1.0 +│ │ └── polymer#2.6.0 +│ ├─┬ paper-input#2.2.0 +│ │ ├── iron-a11y-keys-behavior#2.1.0 +│ │ ├─┬ iron-autogrow-textarea#2.2.0 +│ │ │ ├─┬ iron-behaviors#2.1.1 +│ │ │ │ ├─┬ iron-a11y-keys-behavior#2.1.0 +│ │ │ │ │ └── polymer#2.6.0 +│ │ │ │ └── polymer#2.6.0 +│ │ │ ├── iron-flex-layout#2.0.3 +│ │ │ ├─┬ iron-validatable-behavior#2.1.0 +│ │ │ │ ├── iron-meta#2.1.0 +│ │ │ │ └── polymer#2.6.0 +│ │ │ └── polymer#2.6.0 +│ │ ├── iron-behaviors#2.1.1 +│ │ ├── iron-form-element-behavior#2.1.1 +│ │ ├─┬ iron-input#2.1.2 +│ │ │ ├─┬ iron-a11y-announcer#2.1.0 +│ │ │ │ └── polymer#2.6.0 +│ │ │ ├── iron-validatable-behavior#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ ├─┬ paper-styles#2.1.0 +│ │ │ ├── font-roboto#1.1.0 +│ │ │ ├── iron-flex-layout#2.0.3 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── iron-a11y-announcer#2.1.0 +├─┬ iron-a11y-keys#2.1.1 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ └── polymer#2.6.0 +├── iron-a11y-keys-behavior#2.1.0 +├── iron-ajax#2.1.3 +├── iron-autogrow-textarea#2.2.0 +├── iron-behaviors#2.1.1 +├─┬ iron-checked-element-behavior#2.1.0 +│ ├── iron-form-element-behavior#2.1.1 +│ ├── iron-validatable-behavior#2.1.0 +│ └── polymer#2.6.0 +├─┬ iron-collapse#2.2.0 +│ ├── iron-resizable-behavior#2.1.0 +│ └── polymer#2.6.0 ├─┬ iron-component-page#3.0.1 -│ ├── app-layout#2.0.4 -│ ├── iron-ajax#2.0.6 -│ ├─┬ iron-doc-viewer#3.0.4 -│ │ ├── iron-location#2.0.2 -│ │ ├─┬ marked-element#2.3.2 -│ │ │ ├── marked#0.3.7 -│ │ │ └── polymer#2.3.1 -│ │ ├── paper-styles#2.0.0 -│ │ ├── polymer#2.3.1 -│ │ └─┬ prism-element#2.0.1 -│ │ ├── polymer#2.3.1 -│ │ └── prism#1.9.0 -│ ├─┬ iron-icons#2.0.1 -│ │ ├── iron-icon#2.0.1 -│ │ ├─┬ iron-iconset-svg#2.1.0 -│ │ │ ├── iron-meta#2.0.3 -│ │ │ └── polymer#2.3.1 -│ │ └── polymer#2.3.1 -│ ├─┬ paper-icon-button#2.0.1 -│ │ ├── iron-icon#2.0.1 -│ │ ├─┬ paper-behaviors#2.0.1 -│ │ │ ├── iron-behaviors#2.0.0 -│ │ │ ├── iron-checked-element-behavior#2.0.0 -│ │ │ ├─┬ paper-ripple#2.0.1 -│ │ │ │ ├── iron-a11y-keys-behavior#2.0.1 -│ │ │ │ └── polymer#2.3.1 -│ │ │ └── polymer#2.3.1 -│ │ ├── paper-styles#2.0.0 -│ │ └── polymer#2.3.1 -│ ├── paper-styles#2.0.0 -│ ├─┬ paper-toast#2.0.0 -│ │ ├── iron-a11y-announcer#2.0.0 -│ │ ├── iron-fit-behavior#2.1.0 -│ │ ├─┬ iron-overlay-behavior#2.2.0 -│ │ │ ├── iron-a11y-keys-behavior#2.0.1 -│ │ │ ├─┬ iron-fit-behavior#2.1.0 -│ │ │ │ └── polymer#2.3.1 -│ │ │ ├── iron-resizable-behavior#2.0.1 -│ │ │ └── polymer#2.3.1 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 -├─┬ iron-demo-helpers#2.0.0 -│ ├── font-roboto#1.0.3 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-location#2.0.2 -│ ├── marked-element#2.3.2 -│ ├── polymer#2.3.1 -│ └── prism-element#2.0.1 -├── iron-doc-viewer#3.0.4 -├─┬ iron-dropdown#2.1.0 -│ ├── iron-behaviors#2.0.0 -│ ├── iron-overlay-behavior#2.2.0 -│ ├─┬ neon-animation#2.0.2 -│ │ ├── iron-resizable-behavior#2.0.1 -│ │ ├─┬ iron-selector#2.0.1 -│ │ │ └── polymer#2.3.1 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 -├── iron-fit-behavior#2.1.0 -├── iron-flex-layout#2.0.1 -├── iron-form-element-behavior#2.0.0 -├── iron-icon#2.0.1 -├── iron-icons#2.0.1 -├─┬ iron-iconset#2.0.0 -│ ├── iron-meta#2.0.3 -│ └── polymer#2.3.1 -├── iron-iconset-svg#2.1.0 -├─┬ iron-image#2.1.2 -│ └── polymer#2.3.1 -├── iron-input#2.0.1 -├─┬ iron-jsonp-library#2.0.0 -│ └── polymer#2.3.1 -├─┬ iron-label#2.0.0 -│ └── polymer#2.3.1 -├─┬ iron-list#2.0.12 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-resizable-behavior#2.0.1 -│ ├── iron-scroll-target-behavior#2.0.0 -│ └── polymer#2.3.1 -├─┬ iron-localstorage#2.0.0 -│ └── polymer#2.3.1 -├── iron-location#2.0.2 -├── iron-media-query#2.0.0 -├─┬ iron-menu-behavior#2.0.1 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-selector#2.0.1 -│ └── polymer#2.3.1 -├── iron-meta#2.0.3 -├── iron-overlay-behavior#2.2.0 -├─┬ iron-pages#2.0.1 -│ ├── iron-resizable-behavior#2.0.1 -│ ├── iron-selector#2.0.1 -│ └── polymer#2.3.1 -├─┬ iron-range-behavior#2.0.0 -│ └── polymer#2.3.1 -├── iron-resizable-behavior#2.0.1 -├── iron-scroll-target-behavior#2.0.0 +│ ├── app-layout#2.1.0 +│ ├── iron-ajax#2.1.3 +│ ├─┬ iron-doc-viewer#3.2.0 +│ │ ├── iron-location#2.2.0 +│ │ ├─┬ marked-element#2.4.0 +│ │ │ ├── marked#0.3.18 +│ │ │ └── polymer#2.6.0 +│ │ ├── paper-styles#2.1.0 +│ │ ├── polymer#2.6.0 +│ │ └─┬ prism-element#2.1.0 +│ │ ├── polymer#2.6.0 +│ │ └── prism#1.13.0 +│ ├─┬ iron-icons#2.1.1 +│ │ ├── iron-icon#2.1.0 +│ │ ├─┬ iron-iconset-svg#2.2.0 +│ │ │ ├── iron-meta#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ ├─┬ paper-icon-button#2.2.0 +│ │ ├── iron-icon#2.1.0 +│ │ ├─┬ paper-behaviors#2.1.0 +│ │ │ ├── iron-behaviors#2.1.1 +│ │ │ ├── iron-checked-element-behavior#2.1.0 +│ │ │ ├─┬ paper-ripple#2.1.0 +│ │ │ │ ├── iron-a11y-keys-behavior#2.1.0 +│ │ │ │ └── polymer#2.6.0 +│ │ │ └── polymer#2.6.0 +│ │ ├── paper-styles#2.1.0 +│ │ └── polymer#2.6.0 +│ ├── paper-styles#2.1.0 +│ ├─┬ paper-toast#2.1.0 +│ │ ├── iron-a11y-announcer#2.1.0 +│ │ ├── iron-fit-behavior#2.1.1 +│ │ ├─┬ iron-overlay-behavior#2.3.3 +│ │ │ ├── iron-a11y-keys-behavior#2.1.0 +│ │ │ ├─┬ iron-fit-behavior#2.1.1 +│ │ │ │ └── polymer#2.6.0 +│ │ │ ├── iron-resizable-behavior#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├─┬ iron-demo-helpers#2.1.0 +│ ├── font-roboto#1.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-location#2.2.0 +│ ├── marked-element#2.4.0 +│ ├── polymer#2.6.0 +│ └── prism-element#2.1.0 +├── iron-doc-viewer#3.2.0 +├─┬ iron-dropdown#2.2.0 +│ ├── iron-behaviors#2.1.1 +│ ├── iron-overlay-behavior#2.3.3 +│ ├─┬ neon-animation#2.2.1 +│ │ ├── iron-resizable-behavior#2.1.0 +│ │ ├─┬ iron-selector#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├── iron-fit-behavior#2.1.1 +├── iron-flex-layout#2.0.3 +├─┬ iron-form#2.2.1 +│ ├── iron-ajax#2.1.3 +│ └── polymer#2.6.0 +├── iron-form-element-behavior#2.1.1 +├── iron-icon#2.1.0 +├── iron-icons#2.1.1 +├─┬ iron-iconset#2.1.0 +│ ├── iron-meta#2.1.0 +│ └── polymer#2.6.0 +├── iron-iconset-svg#2.2.0 +├─┬ iron-image#2.2.0 +│ └── polymer#2.6.0 +├── iron-input#2.1.2 +├─┬ iron-jsonp-library#2.1.0 +│ └── polymer#2.6.0 +├─┬ iron-label#2.1.0 +│ └── polymer#2.6.0 +├─┬ iron-list#2.0.13 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-resizable-behavior#2.1.0 +│ ├── iron-scroll-target-behavior#2.1.0 +│ └── polymer#2.6.0 +├─┬ iron-localstorage#2.1.1 +│ └── polymer#2.6.0 +├── iron-location#2.2.0 +├── iron-media-query#2.1.0 +├─┬ iron-menu-behavior#2.1.0 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-selector#2.1.0 +│ └── polymer#2.6.0 +├── iron-meta#2.1.0 +├── iron-overlay-behavior#2.3.3 +├─┬ iron-pages#2.1.0 +│ ├── iron-resizable-behavior#2.1.0 +│ ├── iron-selector#2.1.0 +│ └── polymer#2.6.0 +├─┬ iron-range-behavior#2.1.0 +│ └── polymer#2.6.0 +├── iron-resizable-behavior#2.1.0 +├── iron-scroll-target-behavior#2.1.0 ├─┬ iron-scroll-threshold#2.0.0 -│ ├── iron-scroll-target-behavior#2.0.0 -│ └── polymer#2.3.1 -├── iron-selector#2.0.1 +│ ├── iron-scroll-target-behavior#2.1.0 +│ └── polymer#2.6.0 +├── iron-selector#2.1.0 ├─┬ iron-test-helpers#2.0.0 -│ └── polymer#2.3.1 -├── iron-validatable-behavior#2.0.0 -├── iron-validator-behavior#2.0.0 -├── marked-element#2.3.2 -├── neon-animation#2.0.2 +│ └── polymer#2.6.0 +├── iron-validatable-behavior#2.1.0 +├── iron-validator-behavior#2.1.0 +├── marked-element#2.4.0 +├── neon-animation#2.2.1 ├─┬ note-app-elements#2.1.2 -│ ├── app-storage#2.0.2 -│ ├── font-roboto#1.0.3 -│ ├── iron-autogrow-textarea#2.1.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-icon#2.0.1 -│ ├── iron-icons#2.0.1 -│ ├── iron-input#2.0.1 -│ ├─┬ paper-button#2.0.0 -│ │ ├── iron-flex-layout#2.0.1 -│ │ ├── paper-behaviors#2.0.1 -│ │ ├── paper-styles#2.0.0 -│ │ └── polymer#2.3.1 -│ ├─┬ paper-fab#2.0.0 -│ │ ├── iron-flex-layout#2.0.1 -│ │ ├── iron-icon#2.0.1 -│ │ ├── paper-behaviors#2.0.1 -│ │ ├── paper-styles#2.0.0 -│ │ └── polymer#2.3.1 -│ ├── paper-icon-button#2.0.1 -│ ├── paper-styles#2.0.0 -│ ├── polymer#2.3.1 +│ ├── app-storage#2.1.1 +│ ├── font-roboto#1.1.0 +│ ├── iron-autogrow-textarea#2.2.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-icon#2.1.0 +│ ├── iron-icons#2.1.1 +│ ├── iron-input#2.1.2 +│ ├─┬ paper-button#2.1.0 +│ │ ├── iron-flex-layout#2.0.3 +│ │ ├── paper-behaviors#2.1.0 +│ │ ├── paper-styles#2.1.0 +│ │ └── polymer#2.6.0 +│ ├─┬ paper-fab#2.1.0 +│ │ ├── iron-flex-layout#2.0.3 +│ │ ├── iron-icon#2.1.0 +│ │ ├── paper-behaviors#2.1.0 +│ │ ├── paper-styles#2.1.0 +│ │ └── polymer#2.6.0 +│ ├── paper-icon-button#2.2.0 +│ ├── paper-styles#2.1.0 +│ ├── polymer#2.6.0 │ └── web-animations-js#2.3.1 -├─┬ paper-badge#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-icon#2.0.1 -│ ├── iron-resizable-behavior#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── paper-behaviors#2.0.1 -├── paper-button#2.0.0 -├─┬ paper-card#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-image#2.1.2 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-checkbox#2.0.1 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-checked-element-behavior#2.0.0 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-ripple#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-dialog#2.0.0 -│ ├── iron-overlay-behavior#2.2.0 -│ ├── neon-animation#2.0.2 -│ ├─┬ paper-dialog-behavior#2.0.1 -│ │ ├── iron-overlay-behavior#2.2.0 -│ │ ├── paper-styles#2.0.0 -│ │ └── polymer#2.3.1 -│ └── polymer#2.3.1 -├── paper-dialog-behavior#2.0.1 -├─┬ paper-dialog-scrollable#2.1.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── paper-dialog-behavior#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-drawer-panel#2.0.0 -│ ├── iron-media-query#2.0.0 -│ ├── iron-resizable-behavior#2.0.1 -│ ├── iron-selector#2.0.1 -│ └── polymer#2.3.1 -├─┬ paper-dropdown-menu#2.0.1 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-form-element-behavior#2.0.0 -│ ├── iron-icon#2.0.1 -│ ├── iron-iconset-svg#2.1.0 -│ ├── iron-validatable-behavior#2.0.0 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-input#2.0.5 -│ ├─┬ paper-menu-button#2.0.0 -│ │ ├── iron-a11y-keys-behavior#2.0.1 -│ │ ├── iron-behaviors#2.0.0 -│ │ ├── iron-dropdown#2.1.0 -│ │ ├── iron-fit-behavior#2.1.0 -│ │ ├── neon-animation#2.0.2 -│ │ ├── paper-styles#2.0.0 -│ │ └── polymer#2.3.1 -│ ├── paper-ripple#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── paper-fab#2.0.0 -├─┬ paper-header-panel#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ └── polymer#2.3.1 -├── paper-icon-button#2.0.1 -├── paper-input#2.0.5 -├─┬ paper-item#2.0.0 -│ ├── iron-behaviors#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-listbox#2.0.0 -│ ├── iron-behaviors#2.0.0 -│ ├── iron-menu-behavior#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-material#2.0.0 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── paper-menu-button#2.0.0 -├─┬ paper-progress#2.0.1 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-range-behavior#2.0.0 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-radio-button#2.0.0 -│ ├── iron-checked-element-behavior#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-radio-group#2.0.0 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-menu-behavior#2.0.1 -│ ├── paper-radio-button#2.0.0 -│ └── polymer#2.3.1 -├── paper-ripple#2.0.1 +├─┬ paper-alert-dialog#2.0.1 +│ ├── iron-icon#2.1.0 +│ ├── paper-button#2.1.0 +│ ├─┬ paper-dialog#2.1.1 +│ │ ├── iron-overlay-behavior#2.3.3 +│ │ ├── neon-animation#2.2.1 +│ │ ├─┬ paper-dialog-behavior#2.2.0 +│ │ │ ├── iron-overlay-behavior#2.3.3 +│ │ │ ├── paper-styles#2.1.0 +│ │ │ └── polymer#2.6.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├─┬ paper-badge#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-icon#2.1.0 +│ ├── iron-resizable-behavior#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── paper-behaviors#2.1.0 +├── paper-button#2.1.0 +├─┬ paper-card#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-image#2.2.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-checkbox#2.0.2 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-checked-element-behavior#2.1.0 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-ripple#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-dialog#2.1.1 +│ ├── iron-overlay-behavior#2.3.3 +│ ├── neon-animation#2.2.1 +│ ├─┬ paper-dialog-behavior#2.2.0 +│ │ ├── iron-overlay-behavior#2.3.3 +│ │ ├── paper-styles#2.1.0 +│ │ └── polymer#2.6.0 +│ └── polymer#2.6.0 +├── paper-dialog-behavior#2.2.0 +├─┬ paper-dialog-scrollable#2.2.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── paper-dialog-behavior#2.2.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-drawer-panel#2.1.1 +│ ├── iron-media-query#2.1.0 +│ ├── iron-resizable-behavior#2.1.0 +│ ├── iron-selector#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-dropdown-menu#2.1.0 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-form-element-behavior#2.1.1 +│ ├── iron-icon#2.1.0 +│ ├── iron-iconset-svg#2.2.0 +│ ├── iron-validatable-behavior#2.1.0 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-input#2.2.0 +│ ├─┬ paper-menu-button#2.1.0 +│ │ ├── iron-a11y-keys-behavior#2.1.0 +│ │ ├── iron-behaviors#2.1.1 +│ │ ├── iron-dropdown#2.2.0 +│ │ ├── iron-fit-behavior#2.1.1 +│ │ ├── neon-animation#2.2.1 +│ │ ├── paper-styles#2.1.0 +│ │ └── polymer#2.6.0 +│ ├── paper-ripple#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── paper-fab#2.1.0 +├─┬ paper-header-panel#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ └── polymer#2.6.0 +├── paper-icon-button#2.2.0 +├── paper-input#2.2.0 +├─┬ paper-item#2.1.0 +│ ├── iron-behaviors#2.1.1 +│ ├── iron-flex-layout#2.0.3 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-listbox#2.1.0 +│ ├── iron-behaviors#2.1.1 +│ ├── iron-menu-behavior#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-material#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── paper-menu-button#2.1.0 +├─┬ paper-progress#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-range-behavior#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-radio-button#2.1.0 +│ ├── iron-checked-element-behavior#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-radio-group#2.2.0 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-menu-behavior#2.1.0 +│ ├── paper-radio-button#2.1.0 +│ └── polymer#2.6.0 +├── paper-ripple#2.1.0 ├─┬ paper-scroll-header-panel#2.0.0 -│ ├── iron-resizable-behavior#2.0.1 -│ └── polymer#2.3.1 -├─┬ paper-slider#2.0.4 -│ ├── iron-a11y-keys-behavior#2.0.1 -│ ├── iron-behaviors#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-form-element-behavior#2.0.0 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-input#2.0.5 -│ ├── paper-progress#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-spinner#2.0.0 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── paper-styles#2.0.0 -├─┬ paper-swatch-picker#2.0.1 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-iconset-svg#2.1.0 -│ ├── paper-icon-button#2.0.1 -│ ├── paper-item#2.0.0 -│ ├── paper-listbox#2.0.0 -│ ├── paper-menu-button#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-tabs#2.0.0 -│ ├── iron-behaviors#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── iron-icon#2.0.1 -│ ├── iron-iconset-svg#2.1.0 -│ ├── iron-menu-behavior#2.0.1 -│ ├── iron-resizable-behavior#2.0.1 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-icon-button#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├── paper-toast#2.0.0 -├─┬ paper-toggle-button#2.0.0 -│ ├── iron-checked-element-behavior#2.0.0 -│ ├── paper-behaviors#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-toolbar#2.0.0 -│ ├── iron-flex-layout#2.0.1 -│ ├── paper-styles#2.0.0 -│ └── polymer#2.3.1 -├─┬ paper-tooltip#2.0.1 -│ ├── neon-animation#2.0.2 -│ ├── paper-styles#2.0.0 -│ ├── polymer#2.3.1 -│ └── web-animations-js#2.3.1 -├─┬ platinum-sw#2.0.0 -│ ├── polymer#2.3.1 +│ ├── iron-resizable-behavior#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-slider#2.0.5 +│ ├── iron-a11y-keys-behavior#2.1.0 +│ ├── iron-behaviors#2.1.1 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-form-element-behavior#2.1.1 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-input#2.2.0 +│ ├── paper-progress#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-spinner#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── paper-styles#2.1.0 +├─┬ paper-swatch-picker#2.2.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-iconset-svg#2.2.0 +│ ├── paper-icon-button#2.2.0 +│ ├── paper-item#2.1.0 +│ ├── paper-listbox#2.1.0 +│ ├── paper-menu-button#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-tabs#2.1.0 +│ ├── iron-behaviors#2.1.1 +│ ├── iron-flex-layout#2.0.3 +│ ├── iron-icon#2.1.0 +│ ├── iron-iconset-svg#2.2.0 +│ ├── iron-menu-behavior#2.1.0 +│ ├── iron-resizable-behavior#2.1.0 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-icon-button#2.2.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├── paper-toast#2.1.0 +├─┬ paper-toggle-button#2.1.0 +│ ├── iron-checked-element-behavior#2.1.0 +│ ├── paper-behaviors#2.1.0 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-toolbar#2.1.0 +│ ├── iron-flex-layout#2.0.3 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ paper-tooltip#2.1.1 +│ ├── paper-styles#2.1.0 +│ └── polymer#2.6.0 +├─┬ platinum-sw#2.1.0 +│ ├── polymer#2.6.0 │ └── sw-toolbox#3.6.1 -├── polymer#2.3.1 +├── polymer#2.6.0 ├─┬ polymerfire#2.2.1 -│ ├── app-storage#2.0.2 -│ ├── firebase#4.6.1 -│ └── polymer#2.3.1 -├── prism-element#2.0.1 -├─┬ web-component-tester#6.4.1 +│ ├── app-storage#2.1.1 +│ ├── firebase#4.12.0 +│ └── polymer#2.6.0 +├── prism-element#2.1.0 +├─┬ web-component-tester#6.5.0 (6.6.0-pre.3 available) │ ├── accessibility-developer-tools#2.12.0 │ ├── async#1.5.2 (latest is 2.6.0) │ ├── chai#3.5.0 (latest is 4.1.2) -│ ├── lodash#3.10.1 (3.11.0-npm-packages available, latest is 4.17.4) -│ ├── mocha#3.5.3 (latest is 4.0.1) -│ ├── sinon-chai#2.14.0 +│ ├── lodash#3.10.1 (3.11.0-npm-packages available, latest is 4.17.7-es) +│ ├── mocha#3.5.3 (latest is 5.0.5) +│ ├── sinon-chai#2.14.0 (latest is 3.0.0) │ ├── sinonjs#1.17.1 │ ├── stacky#1.3.2 │ └── test-fixture#3.0.0 -└── webcomponentsjs#1.0.20 +└── webcomponentsjs#1.1.1 ``` diff --git a/bower.json b/bower.json index c77870d1..d5345b59 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "polymer-cdn", - "version": "2.3.1", + "version": "2.6.0", "main": "polymer.js", "homepage": "https://github.com/Download/polymer-cdn", "authors": [ diff --git a/lib/app-layout/.bower.json b/lib/app-layout/.bower.json index b2d0887c..c39866fd 100644 --- a/lib/app-layout/.bower.json +++ b/lib/app-layout/.bower.json @@ -1,6 +1,6 @@ { "name": "app-layout", - "version": "2.0.4", + "version": "2.1.0", "description": "A set of layout elements for your app", "authors": [ "The Polymer Authors" @@ -65,11 +65,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "2.0.4", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.4", - "commit": "623997a76bea695a51de0d4e96e11a8198e367da" + "tag": "v2.1.0", + "commit": "934f0d1cd3a635f5d5e2ed07739f217fe9dfc8ec" }, "_source": "https://github.com/PolymerElements/app-layout.git", "_target": "^2.0.4", diff --git a/lib/app-layout/.github/CODEOWNERS b/lib/app-layout/.github/CODEOWNERS new file mode 100644 index 00000000..b7cc03e4 --- /dev/null +++ b/lib/app-layout/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @keanulee @frankiefu +/.travis.yml @azakus diff --git a/lib/app-layout/.gitignore b/lib/app-layout/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/app-layout/.gitignore +++ b/lib/app-layout/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/app-layout/.travis.yml b/lib/app-layout/.travis.yml index a8e88d57..21c523bc 100644 --- a/lib/app-layout/.travis.yml +++ b/lib/app-layout/.travis.yml @@ -13,6 +13,10 @@ addons: before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) script: - xvfb-run polymer test - >- diff --git a/lib/app-layout/README.md b/lib/app-layout/README.md index cd07604e..84d36d14 100644 --- a/lib/app-layout/README.md +++ b/lib/app-layout/README.md @@ -1,4 +1,4 @@ -# App Layout [![Build Status](https://travis-ci.org/PolymerElements/app-layout.svg?branch=master)](https://travis-ci.org/PolymerElements/app-layout) [![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://beta.webcomponents.org/element/PolymerElements/app-layout) +# App Layout [![Build Status](https://travis-ci.org/PolymerElements/app-layout.svg?branch=master)](https://travis-ci.org/PolymerElements/app-layout) [![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://www.webcomponents.org/element/PolymerElements/app-layout) A collection of elements, along with guidelines and templates that can be used to structure your app’s layout. diff --git a/lib/app-layout/app-box/app-box.d.ts b/lib/app-layout/app-box/app-box.d.ts new file mode 100644 index 00000000..e9b42fb8 --- /dev/null +++ b/lib/app-layout/app-box/app-box.d.ts @@ -0,0 +1,117 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-box/app-box.html + */ + +/// +/// +/// +/// + +/** + * app-box is a container element that can have scroll effects - visual effects based on + * scroll position. For example, the parallax effect can be used to move an image at a slower + * rate than the foreground. + * + * ```html + * + * + * + * ``` + * + * Notice the `background` attribute in the `img` element; this attribute specifies that that + * image is used as the background. By adding the background to the light dom, you can compose + * backgrounds that can change dynamically. Alternatively, the mixin `--app-box-background-front-layer` + * allows to style the background. For example: + * + * ```css + * .parallaxAppBox { + * --app-box-background-front-layer: { + * background-image: url(picture.png); + * }; + * } + * ``` + * + * Finally, app-box can have content inside. For example: + * + * ```html + * + *

Sub title

+ *
+ * ``` + * + * #### Importing the effects + * + * To use the scroll effects, you must explicitly import them in addition to `app-box`: + * + * ```html + * + * ``` + * + * #### List of effects + * + * **parallax-background** + * A simple parallax effect that vertically translates the backgrounds based on a fraction + * of the scroll position. For example: + * + * ```css + * app-header { + * --app-header-background-front-layer: { + * background-image: url(...); + * }; + * } + * ``` + * ```html + * + * App name + * + * ``` + * + * The fraction determines how far the background moves relative to the scroll position. + * This value can be assigned via the `scalar` config value and it is typically a value + * between 0 and 1 inclusive. If `scalar=0`, the background doesn't move away from the header. + * + * ## Styling + * + * Mixin | Description | Default + * ----------------|-------------|---------- + * `--app-box-background-front-layer` | Applies to the front layer of the background | {} + */ +interface AppBoxElement extends Polymer.Element, Polymer.AppScrollEffectsBehavior, Polymer.IronResizableBehavior { + + /** + * The current scroll progress. + */ + _progress: number; + _updateScrollState(scrollTop: any): void; + + /** + * Returns true if this app-box is on the screen. + * That is, visible in the current viewport. + */ + isOnScreen(): boolean; + _getDOMRef(id: any): any; + attached(): void; + _debounceRaf(fn: any): void; + + /** + * Resets the layout. This method is automatically called when the element is attached to the DOM. + */ + resetLayout(): void; + _getElementTop(): any; + _resizeHandler(): void; + + /** + * Returns an object containing the progress value of the scroll effects. + */ + getScrollState(): object|null; +} + +interface HTMLElementTagNameMap { + "app-box": AppBoxElement; +} diff --git a/lib/app-layout/app-drawer-layout/app-drawer-layout.d.ts b/lib/app-layout/app-drawer-layout/app-drawer-layout.d.ts new file mode 100644 index 00000000..0dfc9b94 --- /dev/null +++ b/lib/app-layout/app-drawer-layout/app-drawer-layout.d.ts @@ -0,0 +1,168 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-drawer-layout/app-drawer-layout.html + */ + +/// +/// +/// + +/** + * app-drawer-layout is a wrapper element that positions an app-drawer and other content. When + * the viewport width is smaller than `responsiveWidth`, this element changes to narrow layout. + * In narrow layout, the drawer will be stacked on top of the main content. The drawer will slide + * in/out to hide/reveal the main content. + * + * By default the drawer is aligned to the start, which is left in LTR layouts: + * + * ```html + * + * + * drawer content + * + *
+ * main content + *
+ *
+ * ``` + * + * Align the drawer at the end: + * + * ```html + * + * + * drawer content + * + *
+ * main content + *
+ *
+ * ``` + * + * With an app-header-layout: + * + * ```html + * + * + * drawer-content + * + * + * + * + *
App name
+ *
+ *
+ * + * main content + * + *
+ *
+ * ``` + * + * Add the `drawer-toggle` attribute to elements inside `app-drawer-layout` that toggle the drawer on click events: + * + * ```html + * + * + * drawer-content + * + * + * + * + * + *
App name
+ *
+ *
+ * + * main content + * + *
+ *
+ * ``` + * + * *NOTE:** With app-layout 2.0, the `drawer-toggle` element needs to be manually hidden + * when app-drawer-layout is not in narrow layout. To add this, add the following CSS rule where + * app-drawer-layout is used: + * + * ```css + * app-drawer-layout:not([narrow]) [drawer-toggle] { + * display: none; + * } + * ``` + * + * Add the `fullbleed` attribute to app-drawer-layout to make it fit the size of its container: + * + * ```html + * + * + * drawer content + * + *
+ * main content + *
+ *
+ * ``` + * + * ### Styling + * + * Custom property | Description | Default + * -----------------------------------------|--------------------------------------|--------- + * `--app-drawer-width` | Width of the drawer | 256px + * `--app-drawer-layout-content-transition` | Transition for the content container | none + * + * *NOTE:** If you use with and specify a value for + * `--app-drawer-width`, that value must be accessible by both elements. This can be done by + * defining the value on the `:host` that contains (or `html` if outside + * a shadow root): + * + * ```css + * :host { + * --app-drawer-width: 300px; + * } + * ``` + */ +interface AppDrawerLayoutElement extends Polymer.Element, Polymer.AppLayoutBehavior { + + /** + * If true, ignore `responsiveWidth` setting and force the narrow layout. + */ + forceNarrow: boolean|null|undefined; + + /** + * If the viewport's width is smaller than this value, the panel will change to narrow + * layout. In the mode the drawer will be closed. + */ + responsiveWidth: string|null|undefined; + + /** + * Returns true if it is in narrow layout. This is useful if you need to show/hide + * elements based on the layout. + */ + readonly narrow: boolean|null|undefined; + + /** + * If true, the drawer will initially be opened when in narrow layout mode. + */ + openedWhenNarrow: boolean|null|undefined; + _drawerPosition: string|null|undefined; + + /** + * A reference to the app-drawer element. + */ + readonly drawer: any; + attached(): void; + _updateLayoutStates(): void; + _clickHandler(e: any): void; + _narrowChanged(): void; + _onQueryMatchesChanged(event: any): void; + _computeMediaQuery(forceNarrow: any, responsiveWidth: any): any; +} + +interface HTMLElementTagNameMap { + "app-drawer-layout": AppDrawerLayoutElement; +} diff --git a/lib/app-layout/app-drawer/README.md b/lib/app-layout/app-drawer/README.md index 73a00a4e..72218133 100644 --- a/lib/app-layout/app-drawer/README.md +++ b/lib/app-layout/app-drawer/README.md @@ -35,9 +35,9 @@ Custom property | Description | Defa `--app-drawer-content-container` | Mixin for the drawer content container | {} `--app-drawer-scrim-background` | Background for the scrim | rgba(0, 0, 0, 0.5) -**NOTE:** If you use with and specify a value for +**NOTE:** If you use `` with `` and specify a value for `--app-drawer-width`, that value must be accessible by both elements. This can be done by -defining the value on the `:host` that contains (or `html` if outside +defining the value on the `:host` that contains `` (or `html` if outside a shadow root): ```css diff --git a/lib/app-layout/app-drawer/app-drawer.d.ts b/lib/app-layout/app-drawer/app-drawer.d.ts new file mode 100644 index 00000000..8debab80 --- /dev/null +++ b/lib/app-layout/app-drawer/app-drawer.d.ts @@ -0,0 +1,163 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-drawer/app-drawer.html + */ + +/// +/// + +/** + * app-drawer is a navigation drawer that can slide in from the left or right. + * + * Example: + * + * Align the drawer at the start, which is left in LTR layouts (default): + * + * ```html + * + * ``` + * + * Align the drawer at the end: + * + * ```html + * + * ``` + * + * To make the contents of the drawer scrollable, create a wrapper for the scroll + * content, and apply height and overflow styles to it. + * + * ```html + * + *
+ *
+ * ``` + * + * ### Styling + * + * Custom property | Description | Default + * ---------------------------------|----------------------------------------|-------------------- + * `--app-drawer-width` | Width of the drawer | 256px + * `--app-drawer-content-container` | Mixin for the drawer content container | {} + * `--app-drawer-scrim-background` | Background for the scrim | rgba(0, 0, 0, 0.5) + * + * *NOTE:** If you use `` with `` and specify a value for + * `--app-drawer-width`, that value must be accessible by both elements. This can be done by + * defining the value on the `:host` that contains `` (or `html` if outside + * a shadow root): + * + * ```css + * :host { + * --app-drawer-width: 300px; + * } + * ``` + */ +interface AppDrawerElement extends Polymer.Element { + + /** + * The opened state of the drawer. + */ + opened: boolean|null|undefined; + + /** + * The drawer does not have a scrim and cannot be swiped close. + */ + persistent: boolean|null|undefined; + + /** + * The transition duration of the drawer in milliseconds. + */ + transitionDuration: number|null|undefined; + + /** + * The alignment of the drawer on the screen ('left', 'right', 'start' or 'end'). + * 'start' computes to left and 'end' to right in LTR layout and vice versa in RTL + * layout. + */ + align: string|null|undefined; + + /** + * The computed, read-only position of the drawer on the screen ('left' or 'right'). + */ + readonly position: string|null|undefined; + + /** + * Create an area at the edge of the screen to swipe open the drawer. + */ + swipeOpen: boolean|null|undefined; + + /** + * Trap keyboard focus when the drawer is opened and not persistent. + */ + noFocusTrap: boolean|null|undefined; + + /** + * Disables swiping on the drawer. + */ + disableSwipe: boolean|null|undefined; + _translateOffset: number; + _trackDetails: null; + _drawerState: number; + _boundEscKeydownHandler: null; + _firstTabStop: null; + _lastTabStop: null; + _MIN_FLING_THRESHOLD: number; + _MIN_TRANSITION_VELOCITY: number; + _FLING_TIMING_FUNCTION: string; + _FLING_INITIAL_SLOPE: number; + _DRAWER_STATE: object|null; + attached(): void; + detached(): void; + + /** + * Opens the drawer. + */ + open(): void; + + /** + * Closes the drawer. + */ + close(): void; + + /** + * Toggles the drawer open and close. + */ + toggle(): void; + + /** + * Gets the width of the drawer. + * + * @returns The width of the drawer in pixels. + */ + getWidth(): number; + _isRTL(): any; + _resetPosition(): void; + _escKeydownHandler(event: any): void; + _track(event: any): void; + _trackStart(event: any): void; + _trackMove(event: any): void; + _trackEnd(event: any): void; + _calculateVelocity(event: any, trackDetails: any): any; + _flingDrawer(event: any, trackDetails: any): void; + _styleTransitionDuration(duration: any): void; + _styleTransitionTimingFunction(timingFunction: any): void; + _translateDrawer(x: any): void; + _resetDrawerTranslate(): void; + _resetDrawerState(): void; + + /** + * Resets the layout. + */ + resetLayout(): void; + _setKeyboardFocusTrap(): void; + _tabKeydownHandler(event: any): void; + _openedPersistentChanged(opened: any, persistent: any): void; +} + +interface HTMLElementTagNameMap { + "app-drawer": AppDrawerElement; +} diff --git a/lib/app-layout/app-drawer/app-drawer.html b/lib/app-layout/app-drawer/app-drawer.html index b12f9354..c759f9db 100644 --- a/lib/app-layout/app-drawer/app-drawer.html +++ b/lib/app-layout/app-drawer/app-drawer.html @@ -45,9 +45,9 @@ `--app-drawer-content-container` | Mixin for the drawer content container | {} `--app-drawer-scrim-background` | Background for the scrim | rgba(0, 0, 0, 0.5) -**NOTE:** If you use with and specify a value for +**NOTE:** If you use `` with `` and specify a value for `--app-drawer-width`, that value must be accessible by both elements. This can be done by -defining the value on the `:host` that contains (or `html` if outside +defining the value on the `:host` that contains `` (or `html` if outside a shadow root): ```css diff --git a/lib/app-layout/app-grid/app-grid-style.d.ts b/lib/app-layout/app-grid/app-grid-style.d.ts new file mode 100644 index 00000000..79ea6b80 --- /dev/null +++ b/lib/app-layout/app-grid/app-grid-style.d.ts @@ -0,0 +1,120 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-grid/app-grid-style.html + */ + +/// + +/** + * app-grid is a helper class useful for creating responsive, fluid grid layouts using custom properties. + * Because custom properties can be defined inside a `@media` rule, you can customize the grid layout + * for different responsive breakpoints. + * + * Example: + * + * Import `app-grid-style.html` and include `app-grid-style` in the style of an element's definition. + * Then, add the class `app-grid` to a container such as `ul` or `div`: + * + * ```html + * + * ``` + * In the example above, the grid will take 3 columns per row. + * + * ### Expandible items + * + * In many cases, it's useful to expand an item more than 1 column. To achieve this type of layout, + * you can specify the number of columns the item should expand to by setting the custom property + * `--app-grid-expandible-item-columns`. To indicate which item should expand, apply the mixin + * `--app-grid-expandible-item` to a rule with a selector to the item. For example: + * + *

+ * <template>
+ *   <style include="app-grid-style">
+ *     :host {
+ *       --app-grid-columns: 3;
+ *       --app-grid-item-height: 100px;
+ *       --app-grid-expandible-item-columns: 3;
+ *     }
+ *
+ *     /* Only the first item should expand *\/
+ *     .item:first-child {
+ *       @apply --app-grid-expandible-item;
+ *     }
+ *   </style>
+ * </template>
+ * 
+ * + * ### Preserving the aspect ratio + * + * When the size of a grid item should preserve the aspect ratio, you can add the `has-aspect-ratio` + * attribute to the element with the class `.app-grid`. Now, every item element becomes a wrapper around + * the item content. For example: + * + * ```html + * + * ``` + * + * ### Styling + * + * Custom property | Description | Default + * ----------------------------------------------|------------------------------------------------------------|------------------ + * `--app-grid-columns` | The number of columns per row. | 1 + * `--app-grid-gutter` | The space between two items. | 0px + * `--app-grid-item-height` | The height of the items. | auto + * `--app-grid-expandible-item-columns` | The number of columns an expandible item should expand to. | 1 + */ +interface AppGridElement extends Polymer.Element { +} + +interface HTMLElementTagNameMap { + "app-grid": AppGridElement; +} diff --git a/lib/app-layout/app-header-layout/app-header-layout.d.ts b/lib/app-layout/app-header-layout/app-header-layout.d.ts new file mode 100644 index 00000000..0f598c30 --- /dev/null +++ b/lib/app-layout/app-header-layout/app-header-layout.d.ts @@ -0,0 +1,74 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-header-layout/app-header-layout.html + */ + +/// +/// +/// + +/** + * app-header-layout is a wrapper element that positions an app-header and other content. This + * element uses the document scroll by default, but it can also define its own scrolling region. + * + * Using the document scroll: + * + * ```html + * + * + * + *
App name
+ *
+ *
+ *
+ * main content + *
+ *
+ * ``` + * + * Using an own scrolling region: + * + * ```html + * + * + * + *
App name
+ *
+ *
+ *
+ * main content + *
+ *
+ * ``` + * + * Add the `fullbleed` attribute to app-header-layout to make it fit the size of its container: + * + * ```html + * + * ... + * + * ``` + */ +interface AppHeaderLayoutElement extends Polymer.Element, Polymer.AppLayoutBehavior { + + /** + * If true, the current element will have its own scrolling region. + * Otherwise, it will use the document scroll to control the header. + */ + hasScrollingRegion: boolean|null|undefined; + + /** + * A reference to the app-header element. + */ + readonly header: any; + _updateLayoutStates(): void; +} + +interface HTMLElementTagNameMap { + "app-header-layout": AppHeaderLayoutElement; +} diff --git a/lib/app-layout/app-header-layout/test/app-header-layout.html b/lib/app-layout/app-header-layout/test/app-header-layout.html index 8d46d382..70bc38ab 100644 --- a/lib/app-layout/app-header-layout/test/app-header-layout.html +++ b/lib/app-layout/app-header-layout/test/app-header-layout.html @@ -82,6 +82,7 @@ test('scrolling region', function(done) { headerLayout.hasScrollingRegion = true; + Polymer.dom.flush(); flush(function() { assert.isTrue(header.scrollTarget !== document.documentElement, 'scroller should not point to the document element'); @@ -100,6 +101,7 @@ headerLayout.style.width = '200px'; headerLayout.resetLayout(); + Polymer.dom.flush(); flush(function() { requestAnimationFrame(function() { @@ -121,6 +123,7 @@ test('initial static position header and content', function(done) { assert.isTrue(headerLayout.$.wrapper.classList.contains('initializing')); + Polymer.dom.flush(); flush(function() { assert.isFalse(headerLayout.$.wrapper.classList.contains('initializing')); done(); diff --git a/lib/app-layout/app-header/app-header.d.ts b/lib/app-layout/app-header/app-header.d.ts new file mode 100644 index 00000000..fa738785 --- /dev/null +++ b/lib/app-layout/app-header/app-header.d.ts @@ -0,0 +1,354 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-header/app-header.html + */ + +/// +/// +/// +/// + +/** + * app-header is container element for app-toolbars at the top of the screen that can have scroll + * effects. By default, an app-header moves away from the viewport when scrolling down and + * if using `reveals`, the header slides back when scrolling back up. For example: + * + * ```html + * + * + *
App name
+ *
+ *
+ * ``` + * + * app-header can also condense when scrolling down. To achieve this behavior, the header + * must have a larger height than the `sticky` element in the light DOM. For example: + * + * ```html + * + * + *
App name
+ *
+ *
+ * ``` + * + * In this case the header is initially `96px` tall, and it shrinks to `64px` when scrolling down. + * That is what is meant by "condensing". + * + * ### Sticky element + * + * The element that is positioned fixed to top of the header's `scrollTarget` when a threshold + * is reached, similar to `position: sticky` in CSS. This element **must** be an immediate + * child of app-header. By default, the `sticky` element is the first `app-toolbar that + * is an immediate child of app-header. + * + * ```html + * + * Sticky element + * + * ``` + * + * #### Customizing the sticky element + * + * ```html + * + * + * Sticky element + * + * ``` + * + * ### Scroll target + * + * The app-header's `scrollTarget` property allows to customize the scrollable element to which + * the header responds when the user scrolls. By default, app-header uses the document as + * the scroll target, but you can customize this property by setting the id of the element, e.g. + * + * ```html + *
+ * + * + *
+ * ``` + * + * In this case, the `scrollTarget` property points to the outer div element. Alternatively, + * you can set this property programmatically: + * + * ```js + * appHeader.scrollTarget = document.querySelector("#scrollingRegion"); + * ``` + * + * ## Backgrounds + * app-header has two background layers that can be used for styling when the header is condensed + * or when the scrollable element is scrolled to the top. + * + * ## Scroll effects + * + * Scroll effects are _optional_ visual effects applied in app-header based on scroll position. For example, + * The [Material Design scrolling techniques](https://www.google.com/design/spec/patterns/scrolling-techniques.html) + * recommends effects that can be installed via the `effects` property. e.g. + * + * ```html + * + * App name + * + * ``` + * + * #### Importing the effects + * + * To use the scroll effects, you must explicitly import them in addition to `app-header`: + * + * ```html + * + * ``` + * + * #### List of effects + * + * **blend-background** + * Fades in/out two background elements by applying CSS opacity based on scroll position. + * You can use this effect to smoothly change the background color or image of the header. + * For example, using the mixin `--app-header-background-rear-layer` lets you assign a different + * background when the header is condensed: + * + * ```css + * app-header { + * background-color: red; + * --app-header-background-rear-layer: { + * /* The header is blue when condensed *\/ + * background-color: blue; + * }; + * } + * ``` + * + * **fade-background** + * Upon scrolling past a threshold, this effect will trigger an opacity transition to + * fade in/out the backgrounds. Compared to the `blend-background` effect, + * this effect doesn't interpolate the opacity based on scroll position. + * + * + * **parallax-background** + * A simple parallax effect that vertically translates the backgrounds based on a fraction + * of the scroll position. For example: + * + * ```css + * app-header { + * --app-header-background-front-layer: { + * background-image: url(...); + * }; + * } + * ``` + * ```html + * + * App name + * + * ``` + * + * The fraction determines how far the background moves relative to the scroll position. + * This value can be assigned via the `scalar` config value and it is typically a value + * between 0 and 1 inclusive. If `scalar=0`, the background doesn't move away from the header. + * + * **resize-title** + * Progressively interpolates the size of the title from the element with the `main-title` attribute + * to the element with the `condensed-title` attribute as the header condenses. For example: + * + * ```html + * + * + *

App name

+ *
+ * + *

App name

+ *
+ *
+ * ``` + * + * **resize-snapped-title** + * Upon scrolling past a threshold, this effect fades in/out the titles using opacity transitions. + * Similarly to `resize-title`, the `main-title` and `condensed-title` elements must be placed in the + * light DOM. + * + * **waterfall** + * Toggles the shadow property in app-header to create a sense of depth (as recommended in the + * MD spec) between the header and the underneath content. You can change the shadow by + * customizing the `--app-header-shadow` mixin. For example: + * + * ```css + * app-header { + * --app-header-shadow: { + * box-shadow: inset 0px 5px 2px -3px rgba(0, 0, 0, 0.2); + * }; + * } + * ``` + * + * ```html + * + * + *

App name

+ *
+ *
+ * ``` + * + * **material** + * Installs the waterfall, resize-title, blend-background and parallax-background effects. + * + * ### Content attributes + * + * Attribute | Description | Default + * ----------|---------------------|---------------------------------------- + * `sticky` | Element that remains at the top when the header condenses. | The first app-toolbar in the light DOM. + * + * + * ## Styling + * + * Mixin | Description | Default + * ------|-------------|---------- + * `--app-header-background-front-layer` | Applies to the front layer of the background. | {} + * `--app-header-background-rear-layer` | Applies to the rear layer of the background. | {} + * `--app-header-shadow` | Applies to the shadow. | {} + */ +interface AppHeaderElement extends Polymer.Element, Polymer.AppScrollEffectsBehavior, Polymer.AppLayoutBehavior { + + /** + * If true, the header will automatically collapse when scrolling down. + * That is, the `sticky` element remains visible when the header is fully condensed + * whereas the rest of the elements will collapse below `sticky` element. + * + * By default, the `sticky` element is the first toolbar in the light DOM: + * + * ```html + * + * This toolbar remains on top + * + * + * + * ``` + * + * Additionally, you can specify which toolbar or element remains visible in condensed mode + * by adding the `sticky` attribute to that element. For example: if we want the last + * toolbar to remain visible, we can add the `sticky` attribute to it. + * + * ```html + * + * + * + * This toolbar remains on top + * + * ``` + * + * Note the `sticky` element must be a direct child of `app-header`. + */ + condenses: boolean|null|undefined; + + /** + * Mantains the header fixed at the top so it never moves away. + */ + fixed: boolean|null|undefined; + + /** + * Slides back the header when scrolling back up. + */ + reveals: boolean|null|undefined; + + /** + * Displays a shadow below the header. + */ + shadow: boolean|null|undefined; + + /** + * A cached offsetHeight of the current element. + */ + _height: number; + + /** + * The distance in pixels the header will be translated to when scrolling. + */ + _dHeight: number; + + /** + * The offsetTop of `_stickyEl` + */ + _stickyElTop: number; + + /** + * A reference to the element that remains visible when the header condenses. + */ + _stickyElRef: HTMLElement|null; + + /** + * The header's top value used for the `transformY` + */ + _top: number; + + /** + * The current scroll progress. + */ + _progress: number; + _wasScrollingDown: boolean; + _initScrollTop: number; + _initTimestamp: number; + _lastTimestamp: number; + _lastScrollTop: number; + + /** + * The distance the header is allowed to move away. + */ + readonly _maxHeaderTop: any; + + /** + * Returns a reference to the sticky element. + */ + readonly _stickyEl: HTMLElement|null; + + /** + * Updates the scroll state. + * + * @param forceUpdate (default: false) + */ + _updateScrollState(scrollTop: number, forceUpdate?: boolean): void; + + /** + * Returns true if the current element is on the screen. + * That is, visible in the current viewport. + */ + isOnScreen(): boolean; + + /** + * Returns true if there's content below the current element. + */ + isContentBelow(): boolean; + _getDOMRef(id: any): any; + _updateLayoutStates(): void; + _configChanged(): void; + + /** + * Returns true if the current header is allowed to move as the user scrolls. + */ + _mayMove(): boolean; + + /** + * Returns true if the current header will condense based on the size of the header + * and the `consenses` property. + */ + willCondense(): boolean; + + /** + * Transforms the header. + */ + _transformHeader(y: number): void; + _clamp(v: any, min: any, max: any): any; + _ensureBgContainers(): void; + + /** + * Returns an object containing the progress value of the scroll effects + * and the top position of the header. + */ + getScrollState(): object|null; +} + +interface HTMLElementTagNameMap { + "app-header": AppHeaderElement; +} diff --git a/lib/app-layout/app-layout-behavior/app-layout-behavior.d.ts b/lib/app-layout/app-layout-behavior/app-layout-behavior.d.ts new file mode 100644 index 00000000..b20340ae --- /dev/null +++ b/lib/app-layout/app-layout-behavior/app-layout-behavior.d.ts @@ -0,0 +1,32 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-layout-behavior/app-layout-behavior.html + */ + +/// +/// + +declare namespace Polymer { + + interface AppLayoutBehavior extends Polymer.IronResizableBehavior { + attached(): void; + _appResetLayoutHandler(e: any): void; + _updateLayoutStates(): void; + + /** + * Resets the layout. If you changed the size of this element via CSS + * you can notify the changes by either firing the `iron-resize` event + * or calling `resetLayout` directly. + */ + resetLayout(): void; + _notifyLayoutChanged(): void; + _notifyDescendantResize(): void; + } + + const AppLayoutBehavior: object; +} diff --git a/lib/app-layout/app-layout.d.ts b/lib/app-layout/app-layout.d.ts new file mode 100644 index 00000000..b1e0a642 --- /dev/null +++ b/lib/app-layout/app-layout.d.ts @@ -0,0 +1,19 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-layout.html + */ + +/// +/// +/// +/// +/// +/// +/// +/// + diff --git a/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.d.ts b/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.d.ts new file mode 100644 index 00000000..aa1f13eb --- /dev/null +++ b/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.d.ts @@ -0,0 +1,256 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/app-scroll-effects-behavior.html + */ + +/// +/// +/// + +declare namespace Polymer { + + /** + * `Polymer.AppScrollEffectsBehavior` provides an interface that allows an element to use scrolls effects. + * + * ### Importing the app-layout effects + * + * app-layout provides a set of scroll effects that can be used by explicitly importing + * `app-scroll-effects.html`: + * + * ```html + * + * ``` + * + * The scroll effects can also be used by individually importing + * `app-layout/app-scroll-effects/effects/[effectName].html`. For example: + * + * ```html + * + * ``` + * + * ### Consuming effects + * + * Effects can be consumed via the `effects` property. For example: + * + * ```html + * + * ``` + * + * ### Creating scroll effects + * + * You may want to create a custom scroll effect if you need to modify the CSS of an element + * based on the scroll position. + * + * A scroll effect definition is an object with `setUp()`, `tearDown()` and `run()` functions. + * + * To register the effect, you can use `Polymer.AppLayout.registerEffect(effectName, effectDef)` + * For example, let's define an effect that resizes the header's logo: + * + * ```js + * Polymer.AppLayout.registerEffect('resizable-logo', { + * setUp: function(config) { + * // the effect's config is passed to the setUp. + * this._fxResizeLogo = { logo: Polymer.dom(this).querySelector('[logo]') }; + * }, + * + * run: function(progress) { + * // the progress of the effect + * this.transform('scale3d(' + progress + ', '+ progress +', 1)', this._fxResizeLogo.logo); + * }, + * + * tearDown: function() { + * // clean up and reset of states + * delete this._fxResizeLogo; + * } + * }); + * ``` + * Now, you can consume the effect: + * + * ```html + * + * + * + * ``` + * + * ### Imperative API + * + * ```js + * var logoEffect = appHeader.createEffect('resizable-logo', effectConfig); + * // run the effect: logoEffect.run(progress); + * // tear down the effect: logoEffect.tearDown(); + * ``` + * + * ### Configuring effects + * + * For effects installed via the `effects` property, their configuration can be set + * via the `effectsConfig` property. For example: + * + * ```html + * + * + * ``` + * + * All effects have a `startsAt` and `endsAt` config property. They specify at what + * point the effect should start and end. This value goes from 0 to 1 inclusive. + */ + interface AppScrollEffectsBehavior extends Polymer.IronScrollTargetBehavior { + + /** + * A space-separated list of the effects names that will be triggered when the user scrolls. + * e.g. `waterfall parallax-background` installs the `waterfall` and `parallax-background`. + */ + effects: string|null|undefined; + + /** + * An object that configurates the effects installed via the `effects` property. e.g. + * ```js + * element.effectsConfig = { + * "blend-background": { + * "startsAt": 0.5 + * } + * }; + * ``` + * Every effect has at least two config properties: `startsAt` and `endsAt`. + * These properties indicate when the event should start and end respectively + * and relative to the overall element progress. So for example, if `blend-background` + * starts at `0.5`, the effect will only start once the current element reaches 0.5 + * of its progress. In this context, the progress is a value in the range of `[0, 1]` + * that indicates where this element is on the screen relative to the viewport. + */ + effectsConfig: object|null|undefined; + + /** + * Disables CSS transitions and scroll effects on the element. + */ + disabled: boolean|null|undefined; + + /** + * Allows to set a `scrollTop` threshold. When greater than 0, `thresholdTriggered` + * is true only when the scroll target's `scrollTop` has reached this value. + * + * For example, if `threshold = 100`, `thresholdTriggered` is true when the `scrollTop` + * is at least `100`. + */ + threshold: number|null|undefined; + + /** + * True if the `scrollTop` threshold (set in `scrollTopThreshold`) has + * been reached. + */ + readonly thresholdTriggered: boolean|null|undefined; + + /** + * List of effects handlers that will take place during scroll. + */ + _effectsRunFn: Array|null; + + /** + * List of the effects definitions installed via the `effects` property. + */ + _effects: Array|null; + + /** + * The clamped value of `_scrollTop`. + */ + readonly _clampedScrollTop: any; + + /** + * Overrides the `_scrollHandler`. + */ + _scrollHandler(): void; + + /** + * Updates the scroll state. This method should be overridden + * by the consumer of this behavior. + */ + _updateScrollState(scrollTop: number): void; + + /** + * Returns true if the current element is on the screen. + * That is, visible in the current viewport. This method should be + * overridden by the consumer of this behavior. + */ + isOnScreen(): boolean; + + /** + * Returns true if there's content below the current element. This method + * should be overridden by the consumer of this behavior. + */ + isContentBelow(): boolean; + detached(): void; + + /** + * Creates an effect object from an effect's name that can be used to run + * effects programmatically. + * + * @param effectName The effect's name registered via `Polymer.AppLayout.registerEffect`. + * @param effectConfig The effect config object. (Optional) + * @returns An effect object with the following functions: + * + * * `effect.setUp()`, Sets up the requirements for the effect. + * This function is called automatically before the `effect` function returns. + * * `effect.run(progress, y)`, Runs the effect given a `progress`. + * * `effect.tearDown()`, Cleans up any DOM nodes or element references used by the effect. + * + * Example: + * ```js + * var parallax = element.createEffect('parallax-background'); + * // runs the effect + * parallax.run(0.5, 0); + * ``` + */ + createEffect(effectName: string, effectConfig?: object|null): object|null; + + /** + * Called when `effects` or `effectsConfig` changes. + */ + _effectsChanged(effects: any, effectsConfig: any, isAttached: any): void; + + /** + * Forces layout + */ + _layoutIfDirty(): any; + + /** + * Returns an effect object bound to the current context. + * + * @param effectsConfig The effect config object if the effect accepts config values. (Optional) + */ + _boundEffect(effectDef: object|null, effectsConfig?: object|null): any; + + /** + * Sets up the effects. + */ + _setUpEffect(): void; + + /** + * Tears down the effects. + */ + _tearDownEffects(): void; + + /** + * Runs the effects. + * + * @param p The progress + * @param y The top position of the current element relative to the viewport. + */ + _runEffects(p: number, y: number): void; + + /** + * Override this method to return a reference to a node in the local DOM. + * The node is consumed by a scroll effect. + * + * @param id The id for the node. + */ + _getDOMRef(id: string): void; + _getUndefinedMsg(effectName: any): any; + } + + const AppScrollEffectsBehavior: object; +} diff --git a/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.html b/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.html index 96228908..3f46bfb7 100644 --- a/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.html +++ b/lib/app-layout/app-scroll-effects/app-scroll-effects-behavior.html @@ -179,8 +179,9 @@ * by the consumer of this behavior. * * @method _updateScrollState + * @param {number} scrollTop */ - _updateScrollState: function() {}, + _updateScrollState: function(scrollTop) {}, /** * Returns true if the current element is on the screen. diff --git a/lib/app-layout/app-scroll-effects/app-scroll-effects.d.ts b/lib/app-layout/app-scroll-effects/app-scroll-effects.d.ts new file mode 100644 index 00000000..2d293163 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/app-scroll-effects.d.ts @@ -0,0 +1,18 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/app-scroll-effects.html + */ + +/// +/// +/// +/// +/// +/// +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/blend-background.d.ts b/lib/app-layout/app-scroll-effects/effects/blend-background.d.ts new file mode 100644 index 00000000..9443adb6 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/blend-background.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/blend-background.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/fade-background.d.ts b/lib/app-layout/app-scroll-effects/effects/fade-background.d.ts new file mode 100644 index 00000000..7b59f041 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/fade-background.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/fade-background.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/material.d.ts b/lib/app-layout/app-scroll-effects/effects/material.d.ts new file mode 100644 index 00000000..33208370 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/material.d.ts @@ -0,0 +1,16 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/material.html + */ + +/// +/// +/// +/// +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/parallax-background.d.ts b/lib/app-layout/app-scroll-effects/effects/parallax-background.d.ts new file mode 100644 index 00000000..a6060106 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/parallax-background.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/parallax-background.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/resize-snapped-title.d.ts b/lib/app-layout/app-scroll-effects/effects/resize-snapped-title.d.ts new file mode 100644 index 00000000..07f8febc --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/resize-snapped-title.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/resize-snapped-title.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/resize-title.d.ts b/lib/app-layout/app-scroll-effects/effects/resize-title.d.ts new file mode 100644 index 00000000..bb9871bc --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/resize-title.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/resize-title.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/effects/waterfall.d.ts b/lib/app-layout/app-scroll-effects/effects/waterfall.d.ts new file mode 100644 index 00000000..b424ab99 --- /dev/null +++ b/lib/app-layout/app-scroll-effects/effects/waterfall.d.ts @@ -0,0 +1,12 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * app-scroll-effects/effects/waterfall.html + */ + +/// + diff --git a/lib/app-layout/app-scroll-effects/test/blend-background.html b/lib/app-layout/app-scroll-effects/test/blend-background.html index 3ce462a5..74a96c40 100644 --- a/lib/app-layout/app-scroll-effects/test/blend-background.html +++ b/lib/app-layout/app-scroll-effects/test/blend-background.html @@ -48,7 +48,6 @@ ';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(25);\nvar Constants_1 = __webpack_require__(13);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(12);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(27)))\n\n/***/ }),\n/* 55 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar Node_1 = __webpack_require__(5);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 57 */,\n/* 58 */,\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = __webpack_require__(79);\n\n\n/***/ }),\n/* 79 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar Database_1 = __webpack_require__(32);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(36);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(21);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(26);\nvar INTERNAL = __webpack_require__(111);\nvar TEST_ACCESS = __webpack_require__(112);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(22);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(35);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Event_1 = __webpack_require__(85);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(87);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar ListenComplete_1 = __webpack_require__(88);\nvar Merge_1 = __webpack_require__(89);\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar SyncPoint_1 = __webpack_require__(47);\nvar WriteTree_1 = __webpack_require__(95);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar ViewProcessor_1 = __webpack_require__(91);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar CacheNode_1 = __webpack_require__(18);\nvar ViewCache_1 = __webpack_require__(48);\nvar EventGenerator_1 = __webpack_require__(94);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(8);\nvar Change_1 = __webpack_require__(9);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(92);\nvar Change_1 = __webpack_require__(9);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(10);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar CompleteChildSource_1 = __webpack_require__(93);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(18);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(5);\nvar Change_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar CompoundWrite_1 = __webpack_require__(96);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(49);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(53);\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(55);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ValueIndex_1 = __webpack_require__(38);\nvar PathIndex_1 = __webpack_require__(42);\nvar IndexedFilter_1 = __webpack_require__(24);\nvar LimitedFilter_1 = __webpack_require__(108);\nvar RangedFilter_1 = __webpack_require__(56);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(56);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(21);\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Path_1 = __webpack_require__(2);\nvar Tree_1 = __webpack_require__(110);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(43);\nvar validation_1 = __webpack_require__(7);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(11);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Repo_1 = __webpack_require__(17);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar BrowserPollConnection_1 = __webpack_require__(53);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(34);\nvar PersistentConnection_1 = __webpack_require__(50);\nvar RepoManager_1 = __webpack_require__(26);\nvar Connection_1 = __webpack_require__(52);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[78]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 2\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n __extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n __extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n !exports.isValidKey(parsedUrl.repoInfo.namespace) ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 7\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n __extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 11\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 12\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE\n .updateImmediateChild(childName, newChildNode)\n .updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n __extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 21\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 22\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.intializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return Promise.resolve();\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 32\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if (!namespace || namespace == 'undefined') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host and path.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n host = dataURL.substring(0, slashInd);\n pathString = decodePath(dataURL.substring(slashInd));\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 33\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost;\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n __extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n __extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n __extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 56\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 78\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 79\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 112\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///firebase-database.js","webpack:///../database/dist/cjs/src/core/util/util.js","webpack:///../database/dist/cjs/src/core/util/Path.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js","webpack:///../database/dist/cjs/src/core/snap/ChildrenNode.js","webpack:///../database/dist/cjs/src/core/snap/Node.js","webpack:///../database/dist/cjs/src/core/util/validation.js","webpack:///../database/dist/cjs/src/core/operation/Operation.js","webpack:///../database/dist/cjs/src/core/view/Change.js","webpack:///../database/dist/cjs/src/core/snap/indexes/KeyIndex.js","webpack:///../database/dist/cjs/src/core/snap/nodeFromJSON.js","webpack:///../database/dist/cjs/src/core/storage/storage.js","webpack:///../database/dist/cjs/src/realtime/Constants.js","webpack:///../database/dist/cjs/src/core/snap/indexes/Index.js","webpack:///../database/dist/cjs/src/core/snap/LeafNode.js","webpack:///../database/dist/cjs/src/core/util/SortedMap.js","webpack:///../database/dist/cjs/src/core/Repo.js","webpack:///../database/dist/cjs/src/core/view/CacheNode.js","webpack:///../logger/dist/esm/index.js","webpack:///../logger/dist/esm/src/logger.js","webpack:///../database/dist/cjs/src/api/Reference.js","webpack:///../database/dist/cjs/src/api/DataSnapshot.js","webpack:///../database/dist/cjs/src/core/util/ImmutableTree.js","webpack:///../database/dist/cjs/src/core/view/filter/IndexedFilter.js","webpack:///../database/dist/cjs/src/core/stats/StatsManager.js","webpack:///../database/dist/cjs/src/core/RepoManager.js","webpack:///../database/dist/cjs/src/api/Database.js","webpack:///../database/dist/cjs/src/core/util/libs/parser.js","webpack:///../database/dist/cjs/src/core/RepoInfo.js","webpack:///../database/dist/cjs/src/api/onDisconnect.js","webpack:///../database/dist/cjs/src/api/Query.js","webpack:///../database/dist/cjs/src/core/snap/snap.js","webpack:///../database/dist/cjs/src/core/snap/indexes/ValueIndex.js","webpack:///../database/dist/cjs/src/core/snap/IndexMap.js","webpack:///../database/dist/cjs/src/core/snap/childSet.js","webpack:///../database/dist/cjs/src/core/snap/comparators.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PathIndex.js","webpack:///../database/dist/cjs/src/core/util/ServerValues.js","webpack:///../database/dist/cjs/src/core/SparseSnapshotTree.js","webpack:///../database/dist/cjs/src/core/util/CountedSet.js","webpack:///../database/dist/cjs/src/core/operation/Overwrite.js","webpack:///../database/dist/cjs/src/core/SyncPoint.js","webpack:///../database/dist/cjs/src/core/view/ViewCache.js","webpack:///../database/dist/cjs/src/core/stats/StatsListener.js","webpack:///../database/dist/cjs/src/core/PersistentConnection.js","webpack:///../database/dist/cjs/src/core/util/EventEmitter.js","webpack:///../database/dist/cjs/src/realtime/Connection.js","webpack:///../database/dist/cjs/src/realtime/BrowserPollConnection.js","webpack:///../database/dist/cjs/src/realtime/WebSocketConnection.js","webpack:///../database/dist/cjs/src/core/ServerActions.js","webpack:///../database/dist/cjs/src/core/view/filter/RangedFilter.js","webpack:///./database/index.js","webpack:///../database/dist/cjs/index.js","webpack:///../database/dist/cjs/src/core/storage/DOMStorageWrapper.js","webpack:///../database/dist/cjs/src/core/storage/MemoryStorage.js","webpack:///../database/dist/cjs/src/api/TransactionResult.js","webpack:///../database/dist/cjs/src/core/util/NextPushId.js","webpack:///../database/dist/cjs/src/core/view/EventRegistration.js","webpack:///../database/dist/cjs/src/core/view/Event.js","webpack:///../database/dist/cjs/src/core/SyncTree.js","webpack:///../database/dist/cjs/src/core/operation/AckUserWrite.js","webpack:///../database/dist/cjs/src/core/operation/ListenComplete.js","webpack:///../database/dist/cjs/src/core/operation/Merge.js","webpack:///../database/dist/cjs/src/core/view/View.js","webpack:///../database/dist/cjs/src/core/view/ViewProcessor.js","webpack:///../database/dist/cjs/src/core/view/ChildChangeAccumulator.js","webpack:///../database/dist/cjs/src/core/view/CompleteChildSource.js","webpack:///../database/dist/cjs/src/core/view/EventGenerator.js","webpack:///../database/dist/cjs/src/core/WriteTree.js","webpack:///../database/dist/cjs/src/core/CompoundWrite.js","webpack:///../database/dist/cjs/src/core/SnapshotHolder.js","webpack:///../database/dist/cjs/src/core/AuthTokenProvider.js","webpack:///../database/dist/cjs/src/core/stats/StatsCollection.js","webpack:///../database/dist/cjs/src/core/stats/StatsReporter.js","webpack:///../database/dist/cjs/src/core/view/EventQueue.js","webpack:///../database/dist/cjs/src/core/util/VisibilityMonitor.js","webpack:///../database/dist/cjs/src/core/util/OnlineMonitor.js","webpack:///../database/dist/cjs/src/realtime/TransportManager.js","webpack:///../database/dist/cjs/src/realtime/polling/PacketReceiver.js","webpack:///../database/dist/cjs/src/core/ReadonlyRestClient.js","webpack:///../database/dist/cjs/src/core/view/QueryParams.js","webpack:///../database/dist/cjs/src/core/view/filter/LimitedFilter.js","webpack:///../database/dist/cjs/src/core/Repo_transaction.js","webpack:///../database/dist/cjs/src/core/util/Tree.js","webpack:///../database/dist/cjs/src/api/internal.js","webpack:///../database/dist/cjs/src/api/test_access.js"],"names":["webpackJsonpFirebase","module","exports","__webpack_require__","Object","defineProperty","value","util_1","util_2","util_3","util_4","util_5","util_6","storage_1","util_7","logger_1","logClient","Logger","LUIDGenerator","id","sha1","str","utf8Bytes","stringToByteArray","Sha1","update","sha1Bytes","digest","base64","encodeByteArray","buildLogMessage_","var_args","_i","arguments","length","message","i","Array","isArray","apply","stringify","logger","firstLog_","enableLogging","logger_","persistent","assert","logLevel","LogLevel","VERBOSE","log","bind","SessionStorage","set","remove","get","logWrapper","prefix","concat","error","fatal","Error","warn","warnIfPageIsSecure","window","location","protocol","indexOf","warnAboutUnsupportedMethod","methodName","isInvalidJSONNumber","data","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","fn","isNodeSdk","document","readyState","called_1","wrappedFn_1","body","setTimeout","Math","floor","addEventListener","attachEvent","MIN_NAME","MAX_NAME","nameCompare","a","b","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","key","obj","ObjectToUniqueKey","keys","k","push","sort","splitStringBySize","segsize","len","dataSegs","c","substring","each","forEach","val","bindCallback","callback","context","doubleToIEEE754String","v","s","e","f","ln","bits","abs","pow","min","LN2","round","reverse","join","hexByteString","hexByte","parseInt","substr","toString","toLowerCase","isChromeExtensionContentScript","test","href","isWindowsStoreApp","Windows","UI","errorForServerCode","code","query","reason","path","toUpperCase","INTEGER_REGEXP_","RegExp","intVal","exceptionGuard","stack","callUserCallback","beingCrawled","search","exportPropGetter","object","name","fnGet","setTimeoutNonBlocking","time","timeout","Path","pathOrString","pieceNum","this","pieces_","split","copyTo","pieceNum_","enumerable","configurable","prototype","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","encodeURIComponent","String","slice","begin","parent","pieces","child","childPathObj","childPieces","isEmpty","relativePath","outerPath","innerPath","outer","inner","comparePaths","left","right","leftKeys","rightKeys","cmp","equals","other","j","contains","ValidationPath","errorPrefix_","parts_","byteLength_","max","stringLength","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","tslib_1","Index_1","Node_1","LeafNode_1","PriorityIndex","_super","__extends","compare","aPriority","node","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","NamedNode","MIN","maxPost","LeafNode","makePost","indexValue","priorityNode","Index","PRIORITY_INDEX","EMPTY_NODE","SortedMap_1","snap_1","PriorityIndex_1","KeyIndex_1","IndexMap_1","comparators_1","ChildrenNode","children_","priorityNode_","indexMap_","lazyHash_","validatePriorityNode","SortedMap","NAME_COMPARATOR","IndexMap","Default","isLeafNode","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","front","hasChild","updateImmediateChild","newChildNode","namedNode","newChildren","newIndexMap","newPriority","removeFromIndexes","insert","addToIndexes","updateChild","newImmediateChild","numChildren","count","exportFormat","numKeys","maxKey","allIntegerKeys","forEachChild","childNode","array","hash","toHash_1","priorityHashText","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","iterator","Wrap","next","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","KEY_INDEX","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","call","defineProperties","MAX","KeyIndex","__EMPTY_NODE","__childrenNodeConstructor","Path_1","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","replace","isValidPriority","priority","validateFirebaseDataArg","fnName","argumentNumber","optional","undefined","validateFirebaseData","errorPrefix","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","repoInfo","host","namespace","validateCredential","cred","validateBoolean","bool","validateString","string","validateObject","validateObjectContainsKey","opt_type","safeGet","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","User","Server","forServerTaggedQuery","Change","type","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","assertionError","json","ChildrenNode_1","jsonLeaf","USE_HINZE","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","childSet_1","buildChildSet","NAME_ONLY_COMPARATOR","sortedChildSet","getCompare",".priority","DOMStorageWrapper_1","MemoryStorage_1","createStoragefor","domStorageName","domStorage","setItem","removeItem","DOMStorageWrapper","MemoryStorage","PersistentStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","oldWrapped","newWrapped","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","result","hasNext","LLRBNode","color","RED","copy","reverseTraversal","min_","n","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues_1","nodeFromJSON_1","SparseSnapshotTree_1","SyncTree_1","SnapshotHolder_1","AuthTokenProvider_1","StatsManager_1","StatsReporter_1","StatsListener_1","EventQueue_1","PersistentConnection_1","ReadonlyRestClient_1","Database_1","Repo","repoInfo_","forceRestClient","app","_this","dataUpdateCount","statsListener_","eventQueue_","EventQueue","nextWriteId_","interceptServerDataCallback_","onDisconnect_","SparseSnapshotTree","persistentConnection_","authTokenProvider","AuthTokenProvider","stats_","StatsManager","getCollection","server_","ReadonlyRestClient","onDataUpdate_","onConnectStatus_","authOverride","options","PersistentConnection","onServerInfoUpdate_","addTokenChangeListener","token","refreshAuthToken","statsReporter_","getOrCreateReporter","StatsReporter","transactions_init_","infoData_","SnapshotHolder","infoSyncTree_","SyncTree","startListening","tag","currentHashFn","onComplete","infoEvents","getNode","applyServerOverwrite","stopListening","updateInfo_","serverSyncTree_","listen","status","events","raiseEventsForChangedPath","unlisten","secure","serverTime","offsetNode","offset","Date","getTime","generateServerValues","generateWithValues","timestamp","isMerge","taggedChildren","map","raw","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","changedChildren","applyServerMerge","snap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","updates","updateSnapshot","getNextWriteId_","setWithPriority","newVal","log_","serverValues","newNodeUnresolved","resolveDeferredValueSnapshot","writeId","applyUserOverwrite","queueEvents","put","errorReason","success","clearEvents","ackUserWrite","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","merge","changedPath","resolvedOnDisconnectTree","resolveDeferredValueTree","forEachTree","Empty","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","eventRegistration","addEventRegistration","raiseEventsAtPath","removeEventCallbackForQuery","removeEventRegistration","interrupt","resume","stats","showDelta","console","StatsListener","longestName","reduce","previousValue","currentValue","stat","statsIncrementCounter","metric","incrementCounter","includeStat","__database","Database","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","__webpack_exports__","setLogLevel","level","instances","inst","defaultLogLevel","INFO","defaultLogHandler","instance","logType","args","now","toISOString","DEBUG","info","WARN","ERROR","_logLevel","_logHandler","TypeError","debug","d","onDisconnect_1","TransactionResult_1","NextPushId_1","Query_1","Repo_1","QueryParams_1","validation_1","SyncPoint_1","Reference","repo","QueryParams","DEFAULT","getKey","validateArgCount","getParent","parentPath","getRoot","ref","databaseProp","database","validateCallback","deferred","Deferred","wrapCallback","promise","objectToMerge","newObjectToMerge","transaction","transactionUpdate","applyLocally","catch","promiseComplete","committed","reject","resolve","TransactionResult","startTransaction","setPriority","nextPushId","thennablePushRef","pushRef","then","Promise","onDisconnect","OnDisconnect","Query","__referenceConstructor","SyncPoint","DataSnapshot","ref_","index_","exportVal","toJSON","exists","childPathString","childPath","childRef","hasChildren","getRef","emptyChildrenSingleton","EmptyChildren","ImmutableTree","children","fromObject","tree","childSnap","findRootMostMatchingPathAndValue","predicate","childExistingPathAndValue","findRootMostValueAndPath","subtree","childTree","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","Change_1","IndexedFilter","source","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","getIndex","StatsCollection_1","hashString","collections_","StatsCollection","creatorFunction","reporters_","parser_1","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","appName","dbUrl","databaseFromApp","url","parseRepoInfo","createRepo","deleteRepo","appRepos","toURLString","Reference_1","RepoManager_1","repo_","INTERNAL","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","delete","__awaiter","__generator","_a","decodePath","pathStringDecoded","piece","decodeURIComponent","decodeQuery","queryString","results","startsWith","segment","kv","RepoInfo_1","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","RepoInfo","port","colonInd","slashInd","questionMarkInd","queryParams","parts","Constants_1","persistenceKey","internalHost","needsQueryParam","isCustomHost","isCacheableHost","isDemoHost","updateHost","newHost","connectionURL","params","connURL","pairs","cancel","ValueIndex_1","PathIndex_1","EventRegistration_1","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","PathIndex","VALUE_INDEX","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","getQueryParams","on","cancelCallbackOrContext","ret","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","ValueEventRegistration","ChildEventRegistration","off","validateContextObject","valueCallback","once","userCallback","cancelOrContext","firstCall","onceCallback","err","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","ValueIndex","valueNode","_defaultIndexMap","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","iter","newIndex","indexName","newIndexSet","clone","newIndexes","indexedChildren","existingSnap","SortedMap_2","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","high","middle","base12","root","buildPennant","chunkSize","attachPennant","pennant","isOne","indexPath_","extractChild","aChild","bChild","values","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","CountedSet_1","find","CountedSet","add","self_1","prefixPath","func","item","clear","getCount","Operation_1","Overwrite","OVERWRITE","operationForChild","CacheNode_1","ViewCache_1","View_1","views_","applyOperation","operation","writesCache","optCompleteServerCache","view","events_1","serverCache","serverCacheComplete","eventCache","calcCompleteEventCache","eventCacheComplete","calcCompleteEventChildren","viewCache","ViewCache","View","getInitialEvents","cancelError","removed","cancelEvents","hadCompleteView","hasCompleteView","viewQueryId","getQuery","loadsAllData","getQueryViews","filter","getCompleteServerCache","viewForQuery","getCompleteView","viewExistsForQuery","findValue","eventCache_","serverCache_","updateEventSnap","eventSnap","complete","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","collection_","last_","newStats","delta","app_1","VisibilityMonitor_1","OnlineMonitor_1","Connection_1","ServerActions_1","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","visible_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","VisibilityMonitor","onVisible_","OnlineMonitor","onOnline_","sendRequest","onResponse","curReqNum","msg","r","isDefault","listenSpec","hashFn","sendListen_","req","p","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","credential","isAdmin","token_1","authMethod","isValidFormat","requestData","res","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","request","response","putInternal","sendPut_","queued","reportStats","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","sessionId","handleTimestamp_","sendConnectStats_","restoreState_","clearTimeout","establishConnection_","visible","online","close","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","random","onDataMessage_1","onReady_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","forceRefresh","getToken","accessToken","Connection","CONSTANTS","NODE_ADMIN","serverTimeOffset","q","normalizedPathString","statusCode","explanation","notifyForInvalidToken","queries","shift","clientName","NODE_CLIENT","default","SDK_VERSION","isMobileCordova","isReactNative","currentlyOnline","ServerActions","EventEmitter","allowedEvents_","listeners_","trigger","listeners","validateEventType_","eventData","getInitialEvent","splice","et","TransportManager_1","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","TransportManager","start_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","open","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","t","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","send","start","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","version","h","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","onMessage","closeConnections_","PacketReceiver_1","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","BrowserPollConnection","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","PacketReceiver","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","incrementIncomingBytes_","password","sendNewPolls","closeAfter","pN","handleResponse","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","createElement","shutdown_","myDisconnFrame","removeChild","dataStr","base64data","base64Encode","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","style","display","appendChild","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","script","iframeContents","doc","write","iframe","contentWindow","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","async","onload","onreadystatechange","rstate","parentNode","onerror","process","setWebSocketImpl","impl","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","headers","User-Agent","platform","env","proxy","origin","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","navigator","userAgent","oldAndroidRegex","oldAndroidMatch","match","parseFloat","previouslyFailed","isInMemoryStorage","appendFrame_","fullMess","jsonMess","jsonEval","handleNewFrameCount_","frameCount","extractFrameCount_","isNaN","mess","resetKeepAlive","remainingData","sendString_","clearInterval","setInterval","responsesRequiredToBeHealthy","healthyTimeout","IndexedFilter_1","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","self","startName","endName","registerDatabase","registerService","unused","TEST_ACCESS","DataSnapshot_1","domStorage_","prefix_","prefixedName_","storedVal","getItem","cache_","PUSH_CHARS","lastPushTime","lastRandChars","duplicateTime","timeStampChars","charAt","Event_1","callback_","cancelCallback_","context_","respondsTo","createEvent","change","DataEvent","getEventRunner","ctx","getEventType","cancelCB_1","cb_1","createCancelEvent","CancelEvent","hasAnyCallback","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","getAnyKey","thisKey","every","cb","getPath","AckUserWrite_1","ImmutableTree_1","ListenComplete_1","Merge_1","Overwrite_1","WriteTree_1","listenProvider_","syncPointTree_","pendingWriteTree_","WriteTree","tagToQueryMap_","queryToTagMap_","newData","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","Merge","revert","getWrite","removeWrite","affectedTree_1","AckUserWrite","applyListenComplete","ListenComplete","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","completeCache","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","findIndex","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","listener","createListenerForView_","queryForListening_","tagForQuery_","queryToRemove","tagToRemove","removeTags_","writeIdsToExclude","writeTree","maybeChildSyncPoint","childMap","views_1","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","affectedTree","ACK_USER_WRITE","LISTEN_COMPLETE","MERGE","ViewProcessor_1","EventGenerator_1","query_","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","ViewProcessor","initialServerCache","initialEventCache","newServerCache","newEventCache","viewCache_","eventGenerator_","EventGenerator","cache","path_1","registration","maybeEvent","remaining","existing","completeServerCache","oldViewCache","assertIndexed","generateEventsForChanges_","changes","initialChanges","registrations","generateEventsForChanges","ChildChangeAccumulator_1","CompleteChildSource_1","ProcessorResult","filter_","newViewCache","filterServerNode","accumulator","ChildChangeAccumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","serverNode","completeChildren","completeEventChildren","completeNode","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","calcCompleteChild","changedSnap","oldServerSnap","serverFilter","newServerNode","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","getCompleteChild","newEventSnap","cacheHasChild_","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","changeMap_","oldChange","oldType","getValues","NoCompleteChildSource_","getChildAfterChild","writes_","optCompleteServerCache_","completeServerData","nodes","calcIndexedSlice","eventRegistrations","moves","generateEventsForType_","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","aWrapped","bWrapped","CompoundWrite_1","visibleWrites_","CompoundWrite","allWrites_","lastWriteId_","WriteTreeRef","addWrite","addWrites","record","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","getCompleteNode","treePath","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","shadowingNode","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","findKey","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","writeTree_","existingServerCache","rootmost","rootMostPath","newWrite","applySubtreeWrite_","priorityWrite_1","rootNode_","newSnapshotNode","app_","removeTokenChangeListener","errorMessage","counters_","amount","deepCopy","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","collection","statsToReport_","reportStats_","reportedStats","haveStatsToReport","eventLists_","recursionDepth_","eventDataList","currList","eventPath","EventList","raiseQueuedEventsMatchingPredicate_","sentAll","eventList","raise","events_","eventFn","EventEmitter_1","hidden","visibilityChange","online_","BrowserPollConnection_1","WebSocketConnection_1","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","this_1","toProcess","getListenId_","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","queryStringParameters","authTokenData","authToken","querystring","xhr","XMLHttpRequest","responseText","LimitedFilter_1","RangedFilter_1","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","isViewFromLeft","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","getLimit","copy_","newLimit","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","LimitedFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","rangedFilter_","reverse_","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","TransactionStatus","Tree_1","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","Tree","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","queue","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","forEachAncestor","abortTransactionsOnNode_","forEachDescendant","lastSent","TreeNode","childCount","name_","parent_","pathObj","updateParents_","includeSelf","childrenFirst","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IACvB,CAED,SAAUC,EAAQC,EAASC,GAEjC,YCKAC,QAAAC,eAAAH,EAAA,cAA8CI,OAAA,GAC9C,IAAAC,GAAAJ,EAAA,GACAK,EAAAL,EAAA,GACAM,EAAAN,EAAA,GACAO,EAAAP,EAAA,GACAQ,EAAAR,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AA,GAAAuwB,mBAMAt5B,EAAA21D,QAAA,SAAAC,GACA,MAAAA,GAAAzqC,KAAArK,EAAA2gB,IAOAzhC,EAAAmgB,gBAAA,SAAAA,GACAkS,EAAAd,YAAAG,cAAAvR,uBrFgghBG,KACO,MAAM1c,GACN,KAAUE,OACR","file":"firebase-database.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([0],[\n/* 0 */,\n/* 1 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar util_6 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar util_7 = __webpack_require__(0);\nvar logger_1 = __webpack_require__(22);\nvar logClient = new logger_1.Logger('@firebase/database');\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n logClient.logLevel = logger_1.LogLevel.VERBOSE;\n exports.logger = logClient.log.bind(logClient);\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = \"FIREBASE FATAL ERROR: \" + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n throw new Error(message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.warn(message);\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n/***/ }),\n/* 2 */,\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar util_1 = __webpack_require__(1);\nvar Node_1 = __webpack_require__(6);\nvar LeafNode_1 = __webpack_require__(17);\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar SortedMap_1 = __webpack_require__(18);\nvar Node_1 = __webpack_require__(6);\nvar snap_1 = __webpack_require__(39);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(12);\nvar IndexMap_1 = __webpack_require__(41);\nvar LeafNode_1 = __webpack_require__(17);\nvar comparators_1 = __webpack_require__(43);\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n tslib_1.__extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n/***/ }),\n/* 7 */,\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!exports.isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n/***/ }),\n/* 11 */,\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n tslib_1.__extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\nvar LeafNode_1 = __webpack_require__(17);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(42);\nvar comparators_1 = __webpack_require__(43);\nvar IndexMap_1 = __webpack_require__(41);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = __webpack_require__(82);\nvar MemoryStorage_1 = __webpack_require__(83);\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar snap_1 = __webpack_require__(39);\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = __webpack_require__(45);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar Path_1 = __webpack_require__(3);\nvar SparseSnapshotTree_1 = __webpack_require__(46);\nvar SyncTree_1 = __webpack_require__(88);\nvar SnapshotHolder_1 = __webpack_require__(99);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar AuthTokenProvider_1 = __webpack_require__(100);\nvar StatsManager_1 = __webpack_require__(27);\nvar StatsReporter_1 = __webpack_require__(102);\nvar StatsListener_1 = __webpack_require__(51);\nvar EventQueue_1 = __webpack_require__(103);\nvar PersistentConnection_1 = __webpack_require__(52);\nvar ReadonlyRestClient_1 = __webpack_require__(108);\nvar Database_1 = __webpack_require__(34);\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n/***/ }),\n/* 21 */,\n/* 22 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// CONCATENATED MODULE: ../logger/dist/esm/src/logger.js\n/**\n * Copyright 2017 Google Inc.\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 container for all of the Logger instances\n */\nvar instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nvar LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n/**\n * The default log level\n */\nvar defaultLogLevel = LogLevel.INFO;\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nvar defaultLogHandler = function (instance, logType) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (logType < instance.logLevel)\n return;\n var now = new Date().toISOString();\n switch (logType) {\n /**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\n case LogLevel.DEBUG:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.VERBOSE:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.INFO:\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.WARN:\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.ERROR:\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n default:\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\n }\n};\nvar Logger = /** @class */ (function () {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n function Logger(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The log handler for the Logger instance.\n */\n this._logHandler = defaultLogHandler;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n Object.defineProperty(Logger.prototype, \"logLevel\", {\n get: function () {\n return this._logLevel;\n },\n set: function (val) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Logger.prototype, \"logHandler\", {\n get: function () {\n return this._logHandler;\n },\n set: function (val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The functions below are all based on the `console` interface\n */\n Logger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\n };\n Logger.prototype.log = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\n };\n Logger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\n };\n Logger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\n };\n Logger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\n };\n return Logger;\n}());\n\n\n//# sourceMappingURL=logger.js.map\n\n// CONCATENATED MODULE: ../logger/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"setLogLevel\"] = setLogLevel;\n/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, \"Logger\", function() { return Logger; });\n/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, \"LogLevel\", function() { return LogLevel; });\n/**\n * Copyright 2017 Google Inc.\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\nfunction setLogLevel(level) {\n instances.forEach(function (inst) {\n inst.logLevel = level;\n });\n}\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar onDisconnect_1 = __webpack_require__(37);\nvar TransactionResult_1 = __webpack_require__(84);\nvar util_1 = __webpack_require__(1);\nvar NextPushId_1 = __webpack_require__(85);\nvar Query_1 = __webpack_require__(38);\nvar Repo_1 = __webpack_require__(19);\nvar Path_1 = __webpack_require__(3);\nvar QueryParams_1 = __webpack_require__(109);\nvar validation_1 = __webpack_require__(8);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar SyncPoint_1 = __webpack_require__(49);\nvar Reference = /** @class */ (function (_super) {\n tslib_1.__extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\nvar Path_1 = __webpack_require__(3);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(18);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n/***/ }),\n/* 27 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = __webpack_require__(101);\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n/***/ }),\n/* 28 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Repo_1 = __webpack_require__(19);\nvar util_2 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(35);\nvar validation_1 = __webpack_require__(8);\n__webpack_require__(111);\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.initializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n/***/ }),\n/* 29 */,\n/* 30 */,\n/* 31 */,\n/* 32 */,\n/* 33 */,\n/* 34 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(35);\nvar Path_1 = __webpack_require__(3);\nvar Reference_1 = __webpack_require__(23);\nvar Repo_1 = __webpack_require__(19);\nvar RepoManager_1 = __webpack_require__(28);\nvar util_2 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n Database.prototype.ref = function (path) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference_1.Reference) {\n return this.refFromURL(path.toString());\n }\n return path !== undefined ? this.root_.child(path) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2 /*return*/];\n });\n });\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n/***/ }),\n/* 35 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar RepoInfo_1 = __webpack_require__(36);\nvar util_1 = __webpack_require__(1);\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString) {\n var results = {};\n if (queryString.startsWith('?')) {\n queryString = queryString.substring(1);\n }\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\n var segment = _a[_i];\n if (segment.length === 0) {\n continue;\n }\n var kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n util_1.warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\n }\n }\n return results;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace == 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n var questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = dataURL.length;\n }\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Support `ns` query param if subdomain not already set\n if (subdomain === '' && 'ns' in queryParams) {\n subdomain = queryParams['ns'];\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n/***/ }),\n/* 36 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar Constants_1 = __webpack_require__(15);\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost || this.isCustomHost();\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n/***/ }),\n/* 37 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(8);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n/***/ }),\n/* 38 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar KeyIndex_1 = __webpack_require__(12);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ValueIndex_1 = __webpack_require__(40);\nvar PathIndex_1 = __webpack_require__(44);\nvar util_2 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(3);\nvar validation_1 = __webpack_require__(8);\nvar util_3 = __webpack_require__(0);\nvar EventRegistration_1 = __webpack_require__(86);\nvar util_4 = __webpack_require__(0);\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n/***/ }),\n/* 39 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n/***/ }),\n/* 40 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar Index_1 = __webpack_require__(16);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(1);\nvar nodeFromJSON_1 = __webpack_require__(13);\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n tslib_1.__extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n/***/ }),\n/* 41 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(42);\nvar util_2 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(6);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(12);\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n/***/ }),\n/* 42 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(18);\nvar SortedMap_2 = __webpack_require__(18);\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n/***/ }),\n/* 43 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n/***/ }),\n/* 44 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar Index_1 = __webpack_require__(16);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Node_1 = __webpack_require__(6);\nvar nodeFromJSON_1 = __webpack_require__(13);\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n/***/ }),\n/* 45 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar SparseSnapshotTree_1 = __webpack_require__(46);\nvar LeafNode_1 = __webpack_require__(17);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n/***/ }),\n/* 46 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar CountedSet_1 = __webpack_require__(47);\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n/***/ }),\n/* 47 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n/***/ }),\n/* 48 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar Path_1 = __webpack_require__(3);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n/***/ }),\n/* 49 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(20);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar ViewCache_1 = __webpack_require__(50);\nvar View_1 = __webpack_require__(92);\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n/***/ }),\n/* 50 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\nvar CacheNode_1 = __webpack_require__(20);\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n/***/ }),\n/* 51 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n/***/ }),\n/* 52 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar app_1 = __webpack_require__(7);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(3);\nvar VisibilityMonitor_1 = __webpack_require__(104);\nvar OnlineMonitor_1 = __webpack_require__(105);\nvar util_5 = __webpack_require__(0);\nvar Connection_1 = __webpack_require__(54);\nvar util_6 = __webpack_require__(0);\nvar util_7 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(57);\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body) {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n/***/ }),\n/* 53 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar storage_1 = __webpack_require__(14);\nvar Constants_1 = __webpack_require__(15);\nvar TransportManager_1 = __webpack_require__(106);\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n/***/ }),\n/* 55 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar CountedSet_1 = __webpack_require__(47);\nvar StatsManager_1 = __webpack_require__(27);\nvar PacketReceiver_1 = __webpack_require__(107);\nvar Constants_1 = __webpack_require__(15);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(27);\nvar Constants_1 = __webpack_require__(15);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(29)))\n\n/***/ }),\n/* 57 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 58 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(26);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(6);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */,\n/* 79 */,\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = __webpack_require__(81);\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar Database_1 = __webpack_require__(34);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(38);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(23);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(28);\nvar INTERNAL = __webpack_require__(113);\nvar TEST_ACCESS = __webpack_require__(114);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(24);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(37);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(24);\nvar Event_1 = __webpack_require__(87);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(89);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(25);\nvar ListenComplete_1 = __webpack_require__(90);\nvar Merge_1 = __webpack_require__(91);\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(48);\nvar Path_1 = __webpack_require__(3);\nvar SyncPoint_1 = __webpack_require__(49);\nvar WriteTree_1 = __webpack_require__(97);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(48);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(26);\nvar ViewProcessor_1 = __webpack_require__(93);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar CacheNode_1 = __webpack_require__(20);\nvar ViewCache_1 = __webpack_require__(50);\nvar EventGenerator_1 = __webpack_require__(96);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(9);\nvar Change_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(94);\nvar Change_1 = __webpack_require__(10);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar KeyIndex_1 = __webpack_require__(12);\nvar ImmutableTree_1 = __webpack_require__(25);\nvar Path_1 = __webpack_require__(3);\nvar CompleteChildSource_1 = __webpack_require__(95);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(20);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(6);\nvar Change_1 = __webpack_require__(10);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar CompoundWrite_1 = __webpack_require__(98);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(25);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(6);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(51);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar EventEmitter_1 = __webpack_require__(53);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(53);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(55);\nvar WebSocketConnection_1 = __webpack_require__(56);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(57);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(12);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ValueIndex_1 = __webpack_require__(40);\nvar PathIndex_1 = __webpack_require__(44);\nvar IndexedFilter_1 = __webpack_require__(26);\nvar LimitedFilter_1 = __webpack_require__(110);\nvar RangedFilter_1 = __webpack_require__(58);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(58);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(23);\nvar DataSnapshot_1 = __webpack_require__(24);\nvar Path_1 = __webpack_require__(3);\nvar Tree_1 = __webpack_require__(112);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(45);\nvar validation_1 = __webpack_require__(8);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Repo_1 = __webpack_require__(19);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 113 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(56);\nvar BrowserPollConnection_1 = __webpack_require__(55);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 114 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(36);\nvar PersistentConnection_1 = __webpack_require__(52);\nvar RepoManager_1 = __webpack_require__(28);\nvar Connection_1 = __webpack_require__(54);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[80]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\nvar logger_1 = require(\"@firebase/logger\");\nvar logClient = new logger_1.Logger('@firebase/database');\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n logClient.logLevel = logger_1.LogLevel.VERBOSE;\n exports.logger = logClient.log.bind(logClient);\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = \"FIREBASE FATAL ERROR: \" + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n throw new Error(message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.warn(message);\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n tslib_1.__extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 6\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!exports.isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n tslib_1.__extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 12\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 19\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 20\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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 */\nimport { instances } from './src/logger';\nexport function setLogLevel(level) {\n instances.forEach(function (inst) {\n inst.logLevel = level;\n });\n}\nexport { Logger, LogLevel } from './src/logger';\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 container for all of the Logger instances\n */\nexport var instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n/**\n * The default log level\n */\nvar defaultLogLevel = LogLevel.INFO;\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nvar defaultLogHandler = function (instance, logType) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (logType < instance.logLevel)\n return;\n var now = new Date().toISOString();\n switch (logType) {\n /**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\n case LogLevel.DEBUG:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.VERBOSE:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.INFO:\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.WARN:\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.ERROR:\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n default:\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\n }\n};\nvar Logger = /** @class */ (function () {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n function Logger(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The log handler for the Logger instance.\n */\n this._logHandler = defaultLogHandler;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n Object.defineProperty(Logger.prototype, \"logLevel\", {\n get: function () {\n return this._logLevel;\n },\n set: function (val) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Logger.prototype, \"logHandler\", {\n get: function () {\n return this._logHandler;\n },\n set: function (val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The functions below are all based on the `console` interface\n */\n Logger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\n };\n Logger.prototype.log = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\n };\n Logger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\n };\n Logger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\n };\n Logger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\n };\n return Logger;\n}());\nexport { Logger };\n\n//# sourceMappingURL=logger.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/src/logger.js\n// module id = null\n// module chunks = ","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n tslib_1.__extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 27\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.initializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 28\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n Database.prototype.ref = function (path) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference_1.Reference) {\n return this.refFromURL(path.toString());\n }\n return path !== undefined ? this.root_.child(path) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2 /*return*/];\n });\n });\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString) {\n var results = {};\n if (queryString.startsWith('?')) {\n queryString = queryString.substring(1);\n }\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\n var segment = _a[_i];\n if (segment.length === 0) {\n continue;\n }\n var kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n util_1.warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\n }\n }\n return results;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace == 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n var questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = dataURL.length;\n }\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Support `ns` query param if subdomain not already set\n if (subdomain === '' && 'ns' in queryParams) {\n subdomain = queryParams['ns'];\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost || this.isCustomHost();\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n tslib_1.__extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body) {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 56\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 57\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 58\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 112\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 113\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 114\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/lib/firebase/firebase-firestore.js b/lib/firebase/firebase-firestore.js index 0e530932..819760c7 100644 --- a/lib/firebase/firebase-firestore.js +++ b/lib/firebase/firebase-firestore.js @@ -1,7 +1,7 @@ /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -try{webpackJsonpFirebase([1],{113:function(t,e,n){n(114)},114:function(t,e,n){"use strict";function r(){return Qt}function i(t){Qt=t}function o(t,e){for(var n=[],r=2;rr)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+P(e.length,"argument")+".")}function I(t,e,n,r){if(!(e instanceof Array)||e.length20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=k(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":u("Unknown wrong type: "+typeof t)}function k(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/,n=e.exec(""+t.constructor);if(n&&n.length>1)return n[1]}return null}function R(t,e,n){if(void 0===n)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+_(e)+" argument, but it was undefined.")}function O(t,e,n){y(e,function(e,r){if(n.indexOf(e)<0)throw new zt(Ht.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function M(t,e,n,r){var i=A(r);return new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires its "+_(n)+" argument to be a "+e+", but it was: "+i)}function _(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function P(t,e){return t+" "+e+(1===t?"":"s")}function L(t,e){return te?1:0}function x(t,e){return null!==t&&void 0!==t?!(!e||!t.equals(e)):t===e}function B(t,e){if(t.length!==e.length)return!1;for(var n=0;ne?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function K(t,e){return t===e?0!==t||1/t==1/e:t!==t&&e!==e}function Q(t){return null===t||void 0===t}function G(t){return Pe(t)&&t<=_e&&t>=Me}function W(t,e,n){if(n.equals(ve.INSTANCE)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new Ue(t)}if(n.equals(Te.NAN)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Fe(t)}return new Be(t,e,n)}function H(t){switch(t){case Ht.OK:return u("Treated status OK as error");case Ht.CANCELLED:case Ht.UNKNOWN:case Ht.DEADLINE_EXCEEDED:case Ht.RESOURCE_EXHAUSTED:case Ht.INTERNAL:case Ht.UNAVAILABLE:case Ht.UNAUTHENTICATED:return!1;case Ht.INVALID_ARGUMENT:case Ht.NOT_FOUND:case Ht.ALREADY_EXISTS:case Ht.PERMISSION_DENIED:case Ht.FAILED_PRECONDITION:case Ht.ABORTED:case Ht.OUT_OF_RANGE:case Ht.UNIMPLEMENTED:case Ht.DATA_LOSS:return!0;default:return u("Unknown status code: "+t)}}function z(t){var e=en[t];if(void 0!==e)return X(e)}function X(t){switch(t){case en.OK:return Ht.OK;case en.CANCELLED:return Ht.CANCELLED;case en.UNKNOWN:return Ht.UNKNOWN;case en.DEADLINE_EXCEEDED:return Ht.DEADLINE_EXCEEDED;case en.RESOURCE_EXHAUSTED:return Ht.RESOURCE_EXHAUSTED;case en.INTERNAL:return Ht.INTERNAL;case en.UNAVAILABLE:return Ht.UNAVAILABLE;case en.UNAUTHENTICATED:return Ht.UNAUTHENTICATED;case en.INVALID_ARGUMENT:return Ht.INVALID_ARGUMENT;case en.NOT_FOUND:return Ht.NOT_FOUND;case en.ALREADY_EXISTS:return Ht.ALREADY_EXISTS;case en.PERMISSION_DENIED:return Ht.PERMISSION_DENIED;case en.FAILED_PRECONDITION:return Ht.FAILED_PRECONDITION;case en.ABORTED:return Ht.ABORTED;case en.OUT_OF_RANGE:return Ht.OUT_OF_RANGE;case en.UNIMPLEMENTED:return Ht.UNIMPLEMENTED;case en.DATA_LOSS:return Ht.DATA_LOSS;default:return u("Unknown status code: "+t)}}function Y(t){if(void 0===t)return en.OK;switch(t){case Ht.OK:return en.OK;case Ht.CANCELLED:return en.CANCELLED;case Ht.UNKNOWN:return en.UNKNOWN;case Ht.DEADLINE_EXCEEDED:return en.DEADLINE_EXCEEDED;case Ht.RESOURCE_EXHAUSTED:return en.RESOURCE_EXHAUSTED;case Ht.INTERNAL:return en.INTERNAL;case Ht.UNAVAILABLE:return en.UNAVAILABLE;case Ht.UNAUTHENTICATED:return en.UNAUTHENTICATED;case Ht.INVALID_ARGUMENT:return en.INVALID_ARGUMENT;case Ht.NOT_FOUND:return en.NOT_FOUND;case Ht.ALREADY_EXISTS:return en.ALREADY_EXISTS;case Ht.PERMISSION_DENIED:return en.PERMISSION_DENIED;case Ht.FAILED_PRECONDITION:return en.FAILED_PRECONDITION;case Ht.ABORTED:return en.ABORTED;case Ht.OUT_OF_RANGE:return en.OUT_OF_RANGE;case Ht.UNIMPLEMENTED:return en.UNIMPLEMENTED;case Ht.DATA_LOSS:return en.DATA_LOSS;default:return u("Unknown status code: "+t)}}function J(t){switch(t){case 200:return Ht.OK;case 400:return Ht.INVALID_ARGUMENT;case 401:return Ht.UNAUTHENTICATED;case 403:return Ht.PERMISSION_DENIED;case 404:return Ht.NOT_FOUND;case 409:return Ht.ABORTED;case 416:return Ht.OUT_OF_RANGE;case 429:return Ht.RESOURCE_EXHAUSTED;case 499:return Ht.CANCELLED;case 500:return Ht.UNKNOWN;case 501:return Ht.UNIMPLEMENTED;case 503:return Ht.UNAVAILABLE;case 504:return Ht.DEADLINE_EXCEEDED;default:return t>=200&&t<300?Ht.OK:t>=400&&t<500?Ht.FAILED_PRECONDITION:t>=500&&t<600?Ht.INTERNAL:Ht.UNKNOWN}}function Z(){return fn}function $(){return pn}function tt(){return dn}function et(){return yn}function nt(t,e){e.length>0&&(t.resumeToken=e)}function rt(t,e){c(!Q(t),e+" is missing")}function it(t){return"number"==typeof t?t:"string"==typeof t?parseInt(t,10):u("can't parse "+t)}function ot(t,e,n){return e===n||!e&&n in t}function at(t){if(t.search(xn)>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(Ln.bind.apply(Ln,[void 0].concat(t.split("."))))}catch(e){throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}function st(t,e){var n=function(t){switch(t){case Bn.Added:return 1;case Bn.Modified:case Bn.Metadata:return 2;case Bn.Removed:return 0;default:return u("Unknown ChangeType: "+t)}};return n(t)-n(e)}function ut(t){for(var e="",n=0;n0&&(e=ht(e)),e=ct(t.get(n),e);return ht(e)}function ct(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+t),2===e)return c(t.charAt(0)===ur&&t.charAt(1)===cr,"Non-empty path "+t+" had length 2"),ie.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;on)&&u('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case cr:var s=t.substring(o,a),h=void 0;0===i.length?h=s:(i+=s,h=i,i=""),r.push(h);break;case hr:i+=t.substring(o,a),i+="\0";break;case lr:i+=t.substring(o,a+1);break;default:u('Invalid encoded resource path: "'+t+'"')}o=a+2}return new ie(r)}function ft(t,e){c(0===e,"Unexpected upgrade from version "+e),t.createObjectStore(dr.store,{keyPath:dr.keyPath}),t.createObjectStore(yr.store,{keyPath:yr.keyPath}),t.createObjectStore(wr.store,{keyPath:wr.keyPath}).createIndex(wr.documentTargetsIndex,wr.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(br.store,{keyPath:br.keyPath}).createIndex(br.queryTargetsIndexName,br.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(mr.store),t.createObjectStore(vr.store),t.createObjectStore(pr.store),t.createObjectStore(Ir.store)}function pt(t){return new Wn(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}function dt(t){return c("string"==typeof t,"Persisting non-string stream token not supported."),t}function yt(t){return vt(t,yr.store)}function mt(t){return vt(t,mr.store)}function gt(t){return vt(t,dr.store)}function vt(t,e){return t instanceof Nr?t.store(e):u("Invalid transaction object provided!")}function bt(t){return Tt(t,br.store)}function wt(t){return Tt(t,Ir.store)}function It(t){return Tt(t,wr.store)}function Tt(t,e){return t instanceof Nr?t.store(e):u("Invalid transaction object provided!")}function Et(t){return t instanceof Nr?t.store(vr.store):u("Invalid transaction object provided!")}function St(t){return t.path.toArray()}function Nt(t){return void 0!==t.documents}function Dt(t){if(!t)return new ai;switch(t.type){case"google-auth":return new ui(t.client);case"gapi":return new hi(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new zt(Ht.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function Ct(t){return At(t,["next","error","complete"])}function At(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,i=e;r=0,"Index for document not found"),i=i.delete(n.doc.key)),n.type!==Bn.Removed&&(i=i.add(n.doc),a=i.indexOf(n.doc.key)),{type:Ut(n.type),doc:r,oldIndex:o,newIndex:a}})}function Ut(t){switch(t){case Bn.Added:return"added";case Bn.Modified:case Bn.Metadata:return"modified";case Bn.Removed:return"removed";default:return u("Unknown change type: "+t)}}function Ft(t){t.INTERNAL.registerService("firestore",function(t){return new Ci(t)},g(Ki))}function Vt(t){Ft(t)}Object.defineProperty(e,"__esModule",{value:!0});var qt,jt=n(6),Kt=jt.default.SDK_VERSION;!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(qt=qt||(qt={}));var Qt=qt.ERROR,Gt=function(){function t(){}return t.setPlatform=function(e){t.platform&&u("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||u("Platform not set"),t.platform},t}(),Wt=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ht={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},zt=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return Wt(e,t),e}(Error),Xt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return c(20===e.length,"Invalid auto ID: "+e),e},t}(),Yt=function(){function t(t){q(),this.e=t}return t.fromBase64String=function(e){v("Blob.fromBase64String",arguments,1),T("Blob.fromBase64String","string",1,e),q();try{return new t(Gt.getPlatform().atob(e))}catch(t){throw new zt(Ht.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(v("Blob.fromUint8Array",arguments,1),V(),!(e instanceof Uint8Array))throw M("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return v("Blob.toBase64",arguments,0),q(),Gt.getPlatform().btoa(this.e)},t.prototype.toUint8Array=function(){v("Blob.toUint8Array",arguments,0),V();for(var t=new Uint8Array(this.e.length),e=0;e90)throw new zt(Ht.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new zt(Ht.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this.p=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this.p},enumerable:!0,configurable:!0}),t.prototype.n=function(t){return this._lat===t._lat&&this.p===t.p},t.prototype.r=function(t){return L(this._lat,t._lat)||L(this.p,t.p)},t}(),$t=function(){function t(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}return t}(),te="(default)",ee=function(){function t(t,e){this.projectId=t,this.database=e||te}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===te},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return L(this.projectId,t.projectId)||L(this.database,t.database)},t}(),ne=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),re=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&u("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&u("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):u("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,c(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return c(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return c(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return c(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return c(to)return 1}return t.lengthe.length?1:0},t}(),ie=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(re),oe=/^[_a-zA-Z][_a-zA-Z0-9]*$/,ae=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.isValidIdentifier=function(t){return oe.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;i0&&(e=e.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e=this.root,n=null;!e.isEmpty();){var r=this.comparator(t,e.key);if(0===r){if(e.left.isEmpty())return n?n.key:null;for(e=e.left;!e.right.isEmpty();)e=e.right;return e.key}r<0?e=e.left:r>0&&(n=e,e=e.right)}throw u("Attempted to find predecessor key for a nonexistent key. What gives?")},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(t){return new le(this.root,null,this.comparator,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!1,e)},t.prototype.getReverseIterator=function(t){return new le(this.root,null,this.comparator,!0,t)},t.prototype.getReverseIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!0,e)},t}(),le=function(){function t(t,e,n,r,i){this.resultGenerator=i||null,this.isReverse=r,this.nodeStack=[];for(var o=1;!t.isEmpty();)if(o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse?t.left:t.right;else{if(0===o){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){c(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t,e=this.nodeStack.pop();if(t=this.resultGenerator?this.resultGenerator(e.key,e.value):{key:e.key,value:e.value},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),e=e.left;return t},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return this.resultGenerator?this.resultGenerator(t.key,t.value):{key:t.key,value:t.value}},t}(),fe=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,i=n(t,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n)),r.fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(e,i.key)){if(i.right.isEmpty())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(e,n))}return i.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw u("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw u("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw u("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),pe=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new fe(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();fe.EMPTY=new pe;var de,ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(de=de||(de={}));var me,ge=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":""+t},t.prototype.defaultCompareTo=function(t){return c(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),L(this.typeOrder,t.typeOrder)},t}(),ve=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=de.NullValue,e.internalValue=null,e}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(ge),be=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.BooleanValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(ge),we=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.NumberValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?j(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Ie=function(t){function e(e){return t.call(this,e)||this}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&K(this.internalValue,t.internalValue)},e}(we),Te=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&K(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(we),Ee=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.StringValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Se=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.toDate()},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.equals(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.compareTo(t.internalValue):t instanceof Ne?-1:this.defaultCompareTo(t)},e}(ge),Ne=function(t){function e(e){var n=t.call(this)||this;return n.localWriteTime=e,n.typeOrder=de.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e&&this.localWriteTime.equals(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime.compareTo(t.localWriteTime):t instanceof Se?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(ge),De=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.BlobValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),Ce=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=de.RefValue,r}return ye(e,t),e.prototype.value=function(){return this.key},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.databaseId.equals(t.databaseId)},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:se.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(ge),Ae=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.GeoPointValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),ke=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.ObjectValue,n}return ye(e,t),e.prototype.value=function(){var t={};return this.internalValue.inorderTraversal(function(e,n){t[e]=n.value()}),t},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.equals=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.equals(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),a=L(i.key,o.key)||i.value.compareTo(o.value);if(a)return a}return L(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(c(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var i=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),i)},e.prototype.delete=function(t){if(c(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){c(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e?n.internalValue.get(t)||void 0:void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new he(L)),e}(ge),Re=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=de.ArrayValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.map(function(t){return t.value()})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.equals=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Ve.ASCENDING;this.memoizedOrderBy.push(a===Ve.ASCENDING?Ke:Qe)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){c(null==this.getInequalityFilterField()||!(e instanceof Be)||!e.isInequality()||e.field.equals(this.getInequalityFilterField()),"Query must only have one inequality field."),c(!se.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){c(!se.isDocumentKey(this.path),"No ordering allowed for document query"),c(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),Q(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.equals=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;default:return u("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.equals=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t}(),Be=function(){function t(t,e,n){this.field=t,this.op=e,this.value=n}return t.prototype.matches=function(t){if(this.field.isKeyField()){c(this.value instanceof Ce,"Comparing on key, but filter value not a RefValue");var e=this.value,n=se.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(t){return this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(t){switch(this.op){case xe.LESS_THAN:return t<0;case xe.LESS_THAN_OR_EQUAL:return t<=0;case xe.EQUAL:return 0===t;case xe.GREATER_THAN:return t>0;case xe.GREATER_THAN_OR_EQUAL:return t>=0;default:return u("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==xe.EQUAL},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.op+this.value},t.prototype.equals=function(e){return e instanceof t&&this.op.equals(e.op)&&this.field.equals(e.field)&&this.value.equals(e.value)},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(),Ue=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Fe=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field).value();return"number"==typeof e&&isNaN(e)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Ve=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),qe=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0,"timestamp nanoseconds out of range: "+e),c(e<1e9,"timestamp nanoseconds out of range"+e),c(t>=-62135596800,"timestamp seconds out of range: "+t),c(t<253402300800,"timestamp seconds out of range"+t)}return t.now=function(){return t.fromEpochMilliseconds(Date.now())},t.fromDate=function(e){return t.fromEpochMilliseconds(e.getTime())},t.fromEpochMilliseconds=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.fromISOString=function(e){var n=0,r=Ge.exec(e);if(c(!!r,"invalid timestamp: "+e),r[1]){var i=r[1];i=(i+"000000000").substr(0,9),n=parseInt(i,10)}var o=new Date(e);return new t(Math.floor(o.getTime()/1e3),n)},t.prototype.toDate=function(){return new Date(this.toEpochMilliseconds())},t.prototype.toEpochMilliseconds=function(){return 1e3*this.seconds+this.nanos/1e6},t.prototype.compareTo=function(t){return this.seconds===t.seconds?L(this.nanos,t.nanos):L(this.seconds,t.seconds)},t.prototype.equals=function(t){return t.seconds===this.seconds&&t.nanos===this.nanos},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanos="+this.nanos+")"},t}(),He=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new We(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp.compareTo(t.timestamp)},t.prototype.equals=function(t){return this.timestamp.equals(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanos/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new We(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(me=me||(me={}));var ze,Xe=function(){function t(t,e,n,r,i){void 0===r&&(r=He.MIN),void 0===i&&(i=h()),this.query=t,this.targetId=e,this.purpose=n,this.snapshotVersion=r,this.resumeToken=i}return t.prototype.update=function(e){return new t(this.query,this.targetId,this.purpose,e.snapshotVersion,e.resumeToken)},t.prototype.equals=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.snapshotVersion.equals(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.equals(t.query)},t}(),Ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Je=function(){function t(t){this.fields=t}return t.prototype.equals=function(t){return B(this.fields,t.fields)},t}(),Ze=function(){function t(){}return t.prototype.equals=function(e){return e instanceof t},t.instance=new t,t}(),$e=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.equals=function(t){return this.field.equals(t.field)&&this.transform.equals(t.transform)},t}(),tn=function(){function t(t,e){this.version=t,this.transformResults=e}return t}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(ze=ze||(ze={}));var en,nn=function(){function t(t,e){this.updateTime=t,this.exists=e,c(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof ue&&t.version.equals(this.updateTime):void 0!==this.exists?this.exists?t instanceof ue:null===t||t instanceof ce:(c(this.isNone,"Precondition should be empty"),!0)},t.prototype.equals=function(t){return x(this.updateTime,t.updateTime)&&this.exists===t.exists},t.NONE=new t,t}(),rn=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&c(t.key.equals(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof ue?t.version:He.MIN},t}(),on=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.value=n,i.precondition=r,i.type=ze.Set,i}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by SetMutation.");var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.value.equals(t.value)&&this.precondition.equals(t.precondition)},e}(rn),an=function(t){function e(e,n,r,i){var o=t.call(this)||this;return o.key=e,o.data=n,o.fieldMask=r,o.precondition=i,o.type=ze.Patch,o}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.fieldMask.equals(t.fieldMask)&&this.precondition.equals(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof ue?t.data:ke.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){for(var e=0,n=this.fieldMask.fields;e=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.equals=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),fn=new he(se.comparator),pn=new he(se.comparator),dn=new he(se.comparator),yn=new ln(se.comparator),mn=function(){function t(t,e,n){this.snapshotVersion=t,this.targetChanges=e,this.documentUpdates=n}return t.prototype.addDocumentUpdate=function(t){this.documentUpdates=this.documentUpdates.insert(t.key,t)},t.prototype.handleExistenceFilterMismatch=function(t){this.targetChanges[t]={mapping:new bn,snapshotVersion:He.MIN,currentStatusUpdate:hn.MarkNotCurrent,resumeToken:h()}},t}();!function(t){t[t.None=0]="None",t[t.MarkNotCurrent=1]="MarkNotCurrent",t[t.MarkCurrent=2]="MarkCurrent"}(hn=hn||(hn={}));var gn,vn=et(),bn=function(){function t(){this.docs=vn}return Object.defineProperty(t.prototype,"documents",{get:function(){return this.docs},enumerable:!0,configurable:!0}),t.prototype.add=function(t){this.docs=this.docs.add(t)},t.prototype.delete=function(t){this.docs=this.docs.delete(t)},t.prototype.equals=function(t){return null!==t&&this.docs.equals(t.docs)},t}(),wn=function(){function t(){this.addedDocuments=vn,this.removedDocuments=vn}return t.prototype.applyToKeySet=function(t){var e=t;return this.addedDocuments.forEach(function(t){return e=e.add(t)}),this.removedDocuments.forEach(function(t){return e=e.delete(t)}),e},t.prototype.add=function(t){this.addedDocuments=this.addedDocuments.add(t),this.removedDocuments=this.removedDocuments.delete(t)},t.prototype.delete=function(t){this.addedDocuments=this.addedDocuments.delete(t),this.removedDocuments=this.removedDocuments.add(t)},t.prototype.equals=function(t){return null!==t&&this.addedDocuments.equals(t.addedDocuments)&&this.removedDocuments.equals(t.removedDocuments)},t}(),In=function(){function t(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}return t}(),Tn=function(){function t(t,e){this.targetId=t,this.existenceFilter=e}return t}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(gn=gn||(gn={}));var En=function(){function t(t,e,n,r){void 0===n&&(n=h()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}return t}(),Sn=function(){function t(t,e,n){this.snapshotVersion=t,this.listenTargets=e,this.existenceFilters={},this.targetChanges={},this.documentUpdates=Z(),this.frozen=!1,this.pendingTargetResponses=g(n)}return t.prototype.add=function(t){c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t instanceof In?this.addDocumentChange(t):t instanceof En?this.addTargetChange(t):t instanceof Tn?this.addExistenceFilterChange(t):u("Unknown watch change: "+t)},t.prototype.addChanges=function(t){var e=this;c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t.forEach(function(t){return e.add(t)})},t.prototype.createRemoteEvent=function(){var t=this,e=this.targetChanges;return d(this.targetChanges,function(n){t.isActiveTarget(n)||delete e[n]}),this.frozen=!0,new mn(this.snapshotVersion,e,this.documentUpdates)},t.prototype.ensureTargetChange=function(t){var e=this.targetChanges[t];return e||(e={currentStatusUpdate:hn.None,snapshotVersion:this.snapshotVersion,mapping:new wn,resumeToken:h()},this.targetChanges[t]=e),e},t.prototype.isActiveTarget=function(t){return!f(this.pendingTargetResponses,t)&&f(this.listenTargets,t)},t.prototype.addDocumentChange=function(t){for(var e=!1,n=0,r=t.updatedTargetIds;n4&&"documents"===t.get(4),"tried to deserialize invalid key "+t),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof ve)return{nullValue:"NULL_VALUE"};if(t instanceof be)return{booleanValue:t.value()};if(t instanceof Ie)return{integerValue:""+t.value()};if(t instanceof Te){var e=t.value();if(this.options.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof Ee?{stringValue:t.value()}:t instanceof ke?{mapValue:this.toMapValue(t)}:t instanceof Re?{arrayValue:this.toArrayValue(t)}:t instanceof Se?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ae?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof De?{bytesValue:this.toBytes(t.value())}:t instanceof Ce?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:u("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(ot(t,n,"nullValue"))return ve.INSTANCE;if(ot(t,n,"booleanValue"))return be.of(t.booleanValue);if(ot(t,n,"integerValue"))return new Ie(it(t.integerValue));if(ot(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return Te.NAN;if("Infinity"===t.doubleValue)return Te.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return Te.NEGATIVE_INFINITY}return new Te(t.doubleValue)}if(ot(t,n,"stringValue"))return new Ee(t.stringValue);if(ot(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(ot(t,n,"arrayValue")){rt(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new Re(r.map(function(t){return e.fromValue(t)}))}if(ot(t,n,"timestampValue"))return rt(t.timestampValue,"timestampValue"),new Se(this.fromTimestamp(t.timestampValue));if(ot(t,n,"geoPointValue")){rt(t.geoPointValue,"geoPointValue");var i=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new Ae(new Zt(i,o))}if(ot(t,n,"bytesValue")){rt(t.bytesValue,"bytesValue");var a=this.fromBlob(t.bytesValue);return new De(a)}if(ot(t,n,"referenceValue")){rt(t.referenceValue,"referenceValue");var s=this.fromResourceName(t.referenceValue),c=new ee(s.get(1),s.get(3)),h=new se(this.extractLocalPathFromResourceName(s));return new Ce(c,h)}return u("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return c(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t){return new ue(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasLocalMutations:!1})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=ke.EMPTY;return y(n,function(t,n){r=r.set(new ae([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){c(!!t.found,"Tried to deserialize a found document from a missing document."),rt(t.found.name,"doc.found.name"),rt(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new ue(e,n,r,{hasLocalMutations:!1})},t.prototype.fromMissing=function(t){c(!!t.missing,"Tried to deserialize a missing document from a found document."),c(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new ce(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result_type;return ot(t,e,"found")?this.fromFound(t):ot(t,e,"missing")?this.fromMissing(t):u("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case gn.Added:return"ADD";case gn.Current:return"CURRENT";case gn.NoChange:return"NO_CHANGE";case gn.Removed:return"REMOVE";case gn.Reset:return"RESET";default:return u("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof Tn)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof In){if(t.newDoc instanceof ue){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof ce){var e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof En){var n=void 0;return t.cause&&(n={code:Y(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return u("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.change_type;if(ot(t,n,"targetChange")){rt(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),a=t.targetChange.cause,s=a&&this.fromRpcStatus(a);e=new En(r,i,o,s||null)}else if(ot(t,n,"documentChange")){rt(t.documentChange,"documentChange"),rt(t.documentChange.document,"documentChange.name"),rt(t.documentChange.document.name,"documentChange.document.name"),rt(t.documentChange.document.updateTime,"documentChange.document.updateTime");var c=t.documentChange,h=this.fromName(c.document.name),l=this.fromVersion(c.document.updateTime),f=this.fromFields(c.document.fields||{}),p=new ue(h,l,f,{hasLocalMutations:!1}),d=c.targetIds||[],y=c.removedTargetIds||[];e=new In(d,y,p.key,p)}else if(ot(t,n,"documentDelete")){rt(t.documentDelete,"documentDelete"),rt(t.documentDelete.document,"documentDelete.document");var m=t.documentDelete,h=this.fromName(m.document),l=m.readTime?this.fromVersion(m.readTime):He.forDeletedDoc(),p=new ce(h,l),y=m.removedTargetIds||[];e=new In([],y,p.key,p)}else if(ot(t,n,"documentRemove")){rt(t.documentRemove,"documentRemove"),rt(t.documentRemove.document,"documentRemove");var g=t.documentRemove,h=this.fromName(g.document),y=g.removedTargetIds||[];e=new In([],y,h,null)}else{if(!ot(t,n,"filter"))return u("Unknown change type "+JSON.stringify(t));rt(t.filter,"filter"),rt(t.filter.targetId,"filter.targetId");var v=t.filter,b=v.count||0,w=new cn(b),I=v.targetId;e=new Tn(I,w)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?gn.NoChange:"ADD"===t?gn.Added:"REMOVE"===t?gn.Removed:"CURRENT"===t?gn.Current:"RESET"===t?gn.Reset:u("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!ot(t,t.response_type,"targetChange"))return He.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?He.MIN:e.readTime?this.fromVersion(e.readTime):He.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof on)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof un)e={delete:this.toName(t.key)};else if(t instanceof an)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof sn))return u("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):nn.NONE;if(t.update){rt(t.update.name,"name");var r=this.fromName(t.update.name),i=this.fromFields(t.update.fields||{});if(t.updateMask){var o=this.fromDocumentMask(t.updateMask);return new an(r,i,o,n)}return new on(r,i,n)}if(t.delete){var r=this.fromName(t.delete);return new un(r,n)}if(t.transform){var r=this.fromName(t.transform.document),a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return c(!0===n.exists,'Transforms only support precondition "exists == true"'),new sn(r,a)}return u("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return c(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:u("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?nn.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?nn.exists(t.exists):nn.NONE},t.prototype.fromWriteResult=function(t){var e=this,n=t.updateTime?this.fromVersion(t.updateTime):null,r=null;return t.transformResults&&(r=t.transformResults.map(function(t){return e.fromValue(t)})),new tn(n,r)},t.prototype.fromWriteResults=function(t){var e=this;return(t||[]).map(function(t){return e.fromWriteResult(t)})},t.prototype.toFieldTransform=function(t){return c(t.transform instanceof Ze,"Unknown transform: "+t.transform),{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"}},t.prototype.fromFieldTransform=function(t){c("REQUEST_TIME"===t.setToServerValue,"Unknown transform proto: "+JSON.stringify(t));var e=ae.fromServerFormat(t.fieldPath);return new $e(e,Ze.instance)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;c(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Le.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(ie.EMPTY_PATH);else{var n=t.path;c(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var i=this.toOrder(t.orderBy);i&&(e.structuredQuery.orderBy=i);var o=this.toLimit(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){c(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];e=e.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=n.limit);var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Le(e,a,o,s,u,h)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case me.Listen:return null;case me.ExistenceFilterMismatch:return"existence-filter-mismatch";case me.LimboResolution:return"limbo-document";default:return u("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)},e.targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof Be?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):u("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toLimit=function(t){if(!Q(t))return t},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new qe(r,n)},t.prototype.toDirection=function(t){return Nn[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Ve.ASCENDING;case"DESCENDING":return Ve.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Dn[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return xe.EQUAL;case"GREATER_THAN":return xe.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return xe.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return xe.LESS_THAN;case"LESS_THAN_OR_EQUAL":return xe.LESS_THAN_OR_EQUAL;case"OPERATOR_UNSPECIFIED":return u("Unspecified relation");default:return u("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return ae.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new je(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof Be?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new Be(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Fe?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Ue?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Fe(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Ue(n);case"OPERATOR_UNSPECIFIED":return u("Unspecified filter");default:return u("Unknown filter")}},t.prototype.toDocumentMask=function(t){return{fieldPaths:t.fields.map(function(t){return t.canonicalString()})}},t.prototype.fromDocumentMask=function(t){var e=t.fieldPaths||[],n=e.map(function(t){return ae.fromServerFormat(t)});return new Je(n)},t}(),An=n(115),kn=function(){function t(t){this.wrappedOnOpen=null,this.wrappedOnClose=null,this.wrappedOnMessage=null,this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){c(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){c(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){c(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){c(null!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){c(null!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){c(null!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}(),Rn="Connection",On="gl-js/ fire/"+Kt,Mn=function(){function t(t){this.databaseId=t.databaseId,this.pool=new An.XhrIoPool;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=On,t["google-cloud-resource-prefix"]="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},t.prototype.invoke=function(t,e,n){var r=this,i=this.makeUrl(t);return new Promise(function(s,c){r.pool.getObject(function(h){h.listenOnce(An.EventType.COMPLETE,function(){try{switch(h.getLastErrorCode()){case An.ErrorCode.NO_ERROR:var e=h.getResponseJson();o(Rn,"XHR received:",JSON.stringify(e)),s(e);break;case An.ErrorCode.TIMEOUT:a('RPC "'+t+'" timed out, retrying.'),c(new zt(Ht.DEADLINE_EXCEEDED,"Request time out"));break;case An.ErrorCode.HTTP_ERROR:var n=h.getStatus();a('RPC "'+t+'" failed with status:',n,"response text:",h.getResponseText()),n>0?c(new zt(J(n),"Server responded with status "+h.getStatusText())):(a(Rn,'RPC "'+t+'" failed, retrying.'),c(new zt(Ht.UNAVAILABLE,"Connection failed.")));break;default:u('RPC "'+t+'" failed with unanticipated webchannel error '+h.getLastErrorCode()+": "+h.getLastError()+", giving up.")}}finally{o(Rn,'RPC "'+t+'" completed.'),r.pool.releaseObject(h)}});var l=JSON.stringify(e);o(Rn,"XHR sending: ",i+" "+l);var f={"Content-Type":"text/plain"};r.modifyHeadersForRequest(f,n),h.send(i,"POST",l,f,15)})})},t.prototype.openStream=function(e,n){var r=t.RPC_STREAM_SERVICE_MAPPING[e],i=t.RPC_STREAM_NAME_MAPPING[e];r&&i||u("Unknown RPC name: "+e);var a=[this.baseUrl,"/",r,"/",i,"/channel"],s=Object(An.createWebChannelTransport)(),h={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(h.initMessageHeaders,n);var l=a.join("");o(Rn,"Creating WebChannel: "+l+" "+h);var f=s.createWebChannel(l,h),p=!1,d=!1,y=new kn({sendFn:function(t){d?o(Rn,"Not sending because WebChannel is closed:",t):(p||(o(Rn,"Opening WebChannel transport."),f.open(),p=!0),o(Rn,"WebChannel sending:",t),f.send(t))},closeFn:function(){return f.close()}}),m=function(t,e){f.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return m(An.WebChannel.EventType.OPEN,function(){d||o(Rn,"WebChannel transport opened.")}),m(An.WebChannel.EventType.CLOSE,function(){d||(d=!0,o(Rn,"WebChannel transport closed"),y.callOnClose())}),m(An.WebChannel.EventType.ERROR,function(t){d||(d=!0,o(Rn,"WebChannel transport errored:",t),y.callOnClose(new zt(Ht.UNAVAILABLE,"The operation could not be completed")))}),m(An.WebChannel.EventType.MESSAGE,function(t){if(!d){var e=t.data[0];c(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){o(Rn,"WebChannel received error:",n);var r=n.status,i=z(r),a=n.message;void 0===i&&(i=Ht.INTERNAL,a="Unknown error status: "+r+" with message "+n.message),d=!0,y.callOnClose(new zt(i,a)),f.close()}else o(Rn,"WebChannel received:",e),y.callOnMessage(e)}}),setTimeout(function(){y.callOnOpen()},0),y},t.prototype.makeUrl=function(t){var e=[this.baseUrl,"/","v1beta1"];return e.push("/projects/"),e.push(this.databaseId.projectId),e.push("/databases/"),e.push(this.databaseId.database),e.push("/documents"),e.push(":"),e.push(t),e.join("")},t.RPC_STREAM_SERVICE_MAPPING={Write:"google.firestore.v1beta1.Firestore",Listen:"google.firestore.v1beta1.Firestore"},t.RPC_STREAM_NAME_MAPPING={Write:"Write",Listen:"Listen"},t}(),_n=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return t.prototype.loadConnection=function(t){return Promise.resolve(new Mn(t))},t.prototype.newSerializer=function(t){return new Cn(t,{useProto3Json:!0})},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();Gt.setPlatform(new _n);var Pn,Ln=function(){function t(){for(var t=[],e=0;e=0&&(r.listeners.splice(i,1),n=0===r.listeners.length)}return n?(this.queries.delete(e),this.syncEngine.unlisten(e)):Promise.resolve()},t.prototype.onChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeDocumentMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeQueryMetadataChanges},t.prototype.raiseInitialEvent=function(e){c(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e={query:e.query,docs:e.docs,oldDocs:qn.emptySet(e.docs),docChanges:t.getInitialViewChanges(e),fromCache:e.fromCache,hasPendingWrites:e.hasPendingWrites,syncStateChanged:!0},this.raisedInitialEvent=!0,this.queryObserver.next(e)},t.getInitialViewChanges=function(t){var e=[];return t.docs.forEach(function(t){e.push({type:Bn.Added,doc:t})}),e},t}(),Wn=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=null,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&u("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,i){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,i)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,i)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return e.reduce(function(t,e,n){return t.next(function(){return e})},t.resolve())},t.map=function(e){var n=[],r=!0,i=t.resolve(null);return e.reduce(function(t,e){return t.next(function(t){return r||n.push(t),r=!1,e})},i).next(function(t){return n.push(t),n})},t}(),Hn=function(){function t(){this.isEager=!0,this.sources=[],this.potentialGarbage=et()}return t.prototype.addGarbageSource=function(t){this.sources.push(t),t.setGarbageCollector(this)},t.prototype.removeGarbageSource=function(t){this.sources.splice(this.sources.indexOf(t),1),t.setGarbageCollector(null)},t.prototype.addPotentialGarbageKey=function(t){this.potentialGarbage=this.potentialGarbage.add(t)},t.prototype.collectGarbage=function(t){var e=this,n=[],r=et();return this.potentialGarbage.forEach(function(i){var o=e.documentHasAnyReferences(t,i);n.push(o.next(function(t){return t||(r=r.add(i)),Wn.resolve()}))}),this.potentialGarbage=et(),Wn.waitFor(n).next(function(){return r})},t.prototype.documentHasAnyReferences=function(t,e){var n=Wn.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(t,e)}}).reduce(function(t,e){return t.next(function(t){return t?Wn.resolve(!0):e()})},n)},t}(),zn=function(){function t(t,e,n){this.query=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e){for(var n=et(),r=et(),i=0,o=e.docChanges;i>Jn<=t?n|this.generatorId:(n|this.generatorId)-(1<=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!Q(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),d(t.targetChanges,function(n,r){var i=e.limboKeysByTarget[n];i&&r.currentStatusUpdate===hn.MarkCurrent&&!t.documentUpdates.get(i)&&t.addDocumentUpdate(new ce(i,t.snapshotVersion))}),this.localStore.applyRemoteEvent(t).then(function(n){return e.emitNewSnapsAndNotifyLocalStore(n,t)})},t.prototype.rejectListen=function(t,e){var n=this;this.assertSubscribed("rejectListens()");var r=this.limboKeysByTarget[t];if(r){this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboKeysByTarget[t];var i=new he(se.comparator);i=i.insert(r,new ce(r,He.forDeletedDoc()));var o=new mn(He.MIN,{},i);return this.applyRemoteEvent(o)}var a=this.queryViewsByTarget[t];return c(!!a,"Unknown targetId: "+t),this.localStore.releaseQuery(a.query).then(function(){return n.removeAndCleanupQuery(a).then(function(){n.errorHandler(a.query,e)})})},t.prototype.applySuccessfulWrite=function(t){var e=this;return this.assertSubscribed("applySuccessfulWrite()"),this.processUserCallback(t.batch.batchId,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(t){return n.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new he(L)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(c(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){return this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.limboDocumentRefs.removeReferencesForId(t.targetId),this.gcLimboDocuments()},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.prototype.runTransaction=function(t,e,n){var r=new Nr(this.db,t,e),i=n(r).catch(function(t){return r.abort(),Wn.reject(t)}).toPromise();return r.completionPromise.then(function(){return i})},t.prototype.close=function(){this.db.close()},t}(),Sr=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return pt(this.dbCursor.delete())},t}(),Nr=function(){function t(t,e,n){var r=this;this.aborted=!1,this.transaction=t.transaction(n,e),this.completionPromise=new Promise(function(t,e){r.transaction.onabort=r.transaction.oncomplete=function(e){t()},r.transaction.onerror=function(t){e(t.target.error)}})}return t.prototype.abort=function(){this.aborted||(o("SimpleDb","Aborting transaction."),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return c(!!e,"Object store not part of transaction: "+t),new Dr(e)},t}(),Dr=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(o("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(o("SimpleDb","PUT",this.store.name,"",t),n=this.store.put(t)),pt(n)},t.prototype.get=function(t){var e=this;return pt(this.store.get(t)).next(function(n){return void 0===n&&(n=null),o("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return o("SimpleDb","DELETE",this.store.name,t),pt(this.store.delete(t))},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){o("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateCursor=function(t,e){var n=[];return new Wn(function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(!i)return void r();var o=new Sr(i),a=e(i.primaryKey,i.value,o);a instanceof Wn&&n.push(a),o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}}).next(function(){return Wn.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(c(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}(),Cr=function(){function t(t,e){this.userId=t,this.serializer=e,this.garbageCollector=null}return t.forUser=function(e,n){return c(""!==e.uid,"UserID must not be an empty string."),new t(e.isUnauthenticated()?"":e.uid,n)},t.prototype.start=function(e){var n=this;return t.loadNextBatchIdFromDb(e).next(function(t){return n.nextBatchId=t,gt(e).get(n.userId)}).next(function(t){return t||(t=new dr(n.userId,or,"")),n.metadata=t,n.metadata.lastAcknowledgedBatchId>=n.nextBatchId?n.checkEmpty(e).next(function(t){return c(t,"Reset nextBatchID is only possible when the queue is empty"),n.metadata.lastAcknowledgedBatchId=or,gt(e).put(n.metadata)}):Wn.resolve()})},t.loadNextBatchIdFromDb=function(t){var e=or;return yt(t).iterate({reverse:!0},function(t,n,r){var i=t[0];if(t[1]>e&&(e=n.batchId),""===i)r.done();else{var o=U(i);r.skip([o])}}).next(function(){return e+1})},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).iterate({range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.getNextBatchId=function(t){return Wn.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return Wn.resolve(this.metadata.lastAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;return c(r>this.metadata.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),this.metadata.lastAcknowledgedBatchId=r,this.metadata.lastStreamToken=dt(n),gt(t).put(this.metadata)},t.prototype.getLastStreamToken=function(t){return Wn.resolve(this.metadata.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.metadata.lastStreamToken=dt(e),gt(t).put(this.metadata)},t.prototype.addMutationBatch=function(t,e,n){var r=this,i=this.nextBatchId;this.nextBatchId++;var o=new ar(i,e,n),a=this.serializer.toDbMutationBatch(this.userId,o);return yt(t).put(a).next(function(){for(var e=[],o=0,a=n;oe,"Should have found mutation after "+e),i=n.serializer.fromDbMutationBatch(r)),o.done()}).next(function(){return i})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound(this.keyForBatchId(or),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).loadAll(n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this,r=IDBKeyRange.bound(this.keyForBatchId(or),this.keyForBatchId(e));return yt(t).loadAll(r).next(function(t){return t.map(function(t){return n.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=mr.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];return mt(t).iterate({range:i},function(r,i,a){var s=r[0],c=r[1],h=r[2],l=lt(c);if(s!==n.userId||!e.path.equals(l))return void a.done();var f=n.keyForBatchId(h);return yt(t).get(f).next(function(t){null===t&&u("Dangling document-mutation reference found: "+r+" which points to "+f),o.push(n.serializer.fromDbMutationBatch(t))})}).next(function(){return o})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;c(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,i=r.length+1,o=mr.prefixForPath(this.userId,r),a=(o[1],IDBKeyRange.lowerBound(o)),s=new ln(L);return mt(t).iterate({range:a},function(t,e,o){var a=t[0],u=t[1],c=t[2],h=lt(u);if(a!==n.userId||!r.isPrefixOf(h))return void o.done();h.length===i&&(s=s.add(c))}).next(function(){var e=[],r=[];return s.forEach(function(i){var o=n.keyForBatchId(i);r.push(yt(t).get(o).next(function(t){null===t&&u("Dangling document-mutation reference found, which points to "+o),e.push(n.serializer.fromDbMutationBatch(t))}))}),Wn.waitFor(r).next(function(){return e})})},t.prototype.removeMutationBatches=function(t,e){for(var n=yt(t),r=mt(t),i=[],o=this,a=0,s=e;athis.metadata.highestTargetId?(this.metadata.highestTargetId=r,i.next(function(){return wt(t).put(Ir.key,n.metadata)})):i},t.prototype.removeQueryData=function(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){bt(t).delete(e.targetId)})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return bt(t).iterate({range:i,index:br.queryTargetsIndexName},function(t,r,i){var a=n.serializer.fromDbTarget(r);e.equals(a.query)&&(o=a,i.done())}).next(function(){return o})},t.prototype.addMatchingKeys=function(t,e,n){var r=[],i=It(t);return e.forEach(function(t){var e=ut(t.path);r.push(i.put(new wr(n,e)))}),Wn.waitFor(r)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,i=[],o=It(t);return e.forEach(function(t){var e=ut(t.path);i.push(o.delete([n,e])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(t)}),Wn.waitFor(i)},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=It(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return this.notifyGCForRemovedKeys(t,r).next(function(){return n.delete(r)})},t.prototype.notifyGCForRemovedKeys=function(t,e){var n=this,r=It(t);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:e,keysOnly:!0},function(t,e,r){var i=lt(t[1]),o=new se(i);c(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(o)}):Wn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=It(t),i=et();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=lt(t[1]),o=new se(r);i=i.add(o)}).next(function(){return i})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){c(null!==t,"Persistence Transaction cannot be null for query cache containsKey");var n=ut(e.path),r=IDBKeyRange.bound([n],[F(n)],!1,!0),i=0;return It(t).iterate({index:wr.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){i++,n.done()}).next(function(){return i>0})},t}(),kr=function(){function t(t){this.serializer=t}return t.prototype.addEntry=function(t,e){return Et(t).put(St(e.key),this.serializer.toDbRemoteDocument(e))},t.prototype.removeEntry=function(t,e){return Et(t).delete(St(e))},t.prototype.getEntry=function(t,e){var n=this;return Et(t).get(St(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=$(),i=e.path.toArray(),o=IDBKeyRange.lowerBound(i);return Et(t).iterate({range:o},function(t,i,o){var a=n.serializer.fromDbRemoteDocument(i);e.path.isPrefixOf(a.key.path)?a instanceof ue&&e.matches(a)&&(r=r.insert(a.key,a)):o.done()}).next(function(){return r})},t}(),Rr=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document);if(t.noDocument){var e=se.fromSegments(t.noDocument.path),n=t.noDocument.readTime,r=new We(n.seconds,n.nanos);return new ce(e,He.fromTimestamp(r))}return u("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof ue){var e=this.remoteSerializer.toDocument(t);return new vr(null,e)}var n=t.key.path.toArray(),r=t.version.toTimestamp(),i=new fr(r.seconds,r.nanos);return new vr(new gr(n,i),null)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new yr(t,e.batchId,e.localWriteTime.toEpochMilliseconds(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=We.fromEpochMilliseconds(t.localWriteTimeMs);return new ar(t.batchId,r,n)},t.prototype.fromDbTarget=function(t){var e,n=new We(t.readTime.seconds,t.readTime.nanos),r=He.fromTimestamp(n);return e=Nt(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new Xe(e,t.targetId,me.Listen,r,t.resumeToken)},t.prototype.toDbTarget=function(t){c(me.Listen===t.purpose,"Only queries with purpose "+me.Listen+" may be stored, got "+t.purpose);var e,n=t.snapshotVersion.toTimestamp(),r=new fr(n.seconds,n.nanos);e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),c("string"==typeof t.resumeToken,"Persisting non-string resume token not supported.");var i=t.resumeToken;return new br(t.targetId,t.query.canonicalId(),r,i,0,e)},t}(),Or="There is another tab open with offline persistence enabled. Only one such tab is allowed at a time. The other tab must be closed or persistence must be disabled.",Mr=function(){function t(e,n){this.ownerId=this.generateOwnerId(),this.dbName=e+t.MAIN_DATABASE,this.serializer=new Rr(n),this.localStoragePrefix=e}return t.prototype.start=function(){var e=this;return t.isAvailable()?(c(!this.started,"IndexedDbPersistence double-started!"),this.started=!0,Er.openOrCreate(this.dbName,1,ft).then(function(t){e.simpleDb=t}).then(function(){return e.tryAcquireOwnerLease()}).then(function(){e.scheduleOwnerLeaseRefreshes(),e.attachWindowUnloadHook()})):(this.persistenceError=new zt(Ht.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."),Promise.reject(this.persistenceError))},t.prototype.shutdown=function(){var t=this;return c(this.started,"IndexedDbPersistence shutdown without start!"),this.started=!1,this.detachWindowUnloadHook(),this.stopOwnerLeaseRefreshes(),this.releaseOwnerLease().then(function(){t.simpleDb.close()})},t.prototype.getMutationQueue=function(t){return Cr.forUser(t,this.serializer)},t.prototype.getQueryCache=function(){return new Ar(this.serializer)},t.prototype.getRemoteDocumentCache=function(){return new kr(this.serializer)},t.prototype.runTransaction=function(t,e){var n=this;return this.persistenceError?Promise.reject(this.persistenceError):(o("IndexedDbPersistence","Starting transaction:",t),this.simpleDb.runTransaction("readwrite",Tr,function(t){return n.ensureOwnerLease(t).next(function(){return e(t)})}))},t.isAvailable=function(){return Er.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.tryAcquireOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){if(t.validOwner(e))return o("IndexedDbPersistence","Valid owner already. Failing. Current owner:",e),t.persistenceError=new zt(Ht.FAILED_PRECONDITION,Or),Wn.reject(t.persistenceError);var r=new pr(t.ownerId,Date.now());return o("IndexedDbPersistence","No valid owner. Acquiring owner lease. Current owner:",e,"New owner:",r),n.put("owner",r)})})},t.prototype.releaseOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){return null!==e&&e.ownerId===t.ownerId?(o("IndexedDbPersistence","Releasing owner lease."),n.delete("owner")):Wn.resolve()})})},t.prototype.ensureOwnerLease=function(t){var e=this;return t.store(pr.store).get("owner").next(function(t){return null===t||t.ownerId!==e.ownerId?(e.persistenceError=new zt(Ht.FAILED_PRECONDITION,Or),Wn.reject(e.persistenceError)):Wn.resolve()})},t.prototype.validOwner=function(t){var e=Date.now(),n=e-5e3,r=e;return!(null===t||t.leaseTimestampMsr?(a("Persistence owner-lease is in the future. Discarding.",t),1):t.ownerId===this.getZombiedOwnerId()))},t.prototype.scheduleOwnerLeaseRefreshes=function(){var t=this;this.ownerLeaseRefreshHandle=setInterval(function(){t.runTransaction("Refresh owner timestamp",function(e){return e.store(pr.store).put("owner",new pr(t.ownerId,Date.now()))}).catch(function(e){a(e),t.stopOwnerLeaseRefreshes()})},4e3)},t.prototype.stopOwnerLeaseRefreshes=function(){this.ownerLeaseRefreshHandle&&(clearInterval(this.ownerLeaseRefreshHandle),this.ownerLeaseRefreshHandle=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;this.windowUnloadHandler=function(){t.setZombiedOwnerId(t.ownerId),t.shutdown()},window.addEventListener("unload",this.windowUnloadHandler)},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.getZombiedOwnerId=function(){try{var t=window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());return o("IndexedDbPersistence","Zombied ownerID from LocalStorage:",t),t}catch(t){return a("IndexedDbPersistence","Failed to get zombie owner id.",t),null}},t.prototype.setZombiedOwnerId=function(t){try{null===t?window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey()):window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(),t)}catch(t){a("IndexedDbPersistence","Failed to set zombie owner id.",t)}},t.prototype.zombiedOwnerLocalStorageKey=function(){return this.localStoragePrefix+"zombiedOwnerId"},t.prototype.generateOwnerId=function(){return Xt.newId()},t.MAIN_DATABASE="main",t}(),_r=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.remoteDocumentCache.getEntry(t,e).next(function(r){return n.computeLocalDocument(t,e,r)})},t.prototype.getDocuments=function(t,e){var n=this,r=[],i=Z();return e.forEach(function(e){r.push(n.getDocument(t,e).next(function(t){t||(t=new ce(e,He.forDeletedDoc())),i=i.insert(e,t)}))}),Wn.waitFor(r).next(function(){return i})},t.prototype.getDocumentsMatchingQuery=function(t,e){return se.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new se(e)).next(function(t){var e=$();return t instanceof ue&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(e){return r.computeLocalDocuments(t,e)}).next(function(i){return n=i,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(e){for(var i=et(),o=0,a=e;o0?e.mutationQueue.removeMutationBatches(t,n):Wn.resolve()})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations",function(n){var r,i=We.now();return e.mutationQueue.addMutationBatch(n,i,t).next(function(t){r=t;var i=r.keys();return e.localDocuments.getDocuments(n,i)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch",function(n){var r;return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){if(e.shouldHoldBatchResult(t.commitVersion))return e.heldBatchResults.push(t),r=et(),Wn.resolve();var i=new Pr(e.remoteDocuments);return e.releaseBatchResults(n,[t],i).next(function(t){return r=t,i.apply(n)})}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch",function(n){var r,i;return e.mutationQueue.lookupMutationBatch(n,t).next(function(i){return c(null!=i,"Attempt to reject nonexistent batch!"),r=i,e.mutationQueue.getHighestAcknowledgedBatchId(n).next(function(e){return c(t>e,"Acknowledged batches can't be rejected."),r})}).next(function(){return e.removeMutationBatch(n,r)}).next(function(t){return i=t,e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,i)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){return this.queryCache.getLastRemoteSnapshotVersion()},t.prototype.applyRemoteEvent=function(t){var e=this,n=new Pr(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event",function(r){var i=[];d(t.targetChanges,function(t,n){var o=e.targetIds[t];if(o){var a=n.mapping;if(a)if(a instanceof bn)i.push(e.queryCache.removeMatchingKeysForTargetId(r,t).next(function(){return e.queryCache.addMatchingKeys(r,a.documents,t)}));else{if(!(a instanceof wn))return u("Unknown mapping type: "+JSON.stringify(a));i.push(e.queryCache.removeMatchingKeys(r,a.removedDocuments,t).next(function(){return e.queryCache.addMatchingKeys(r,a.addedDocuments,t)}))}var s=n.resumeToken;s.length>0&&(o=o.update({resumeToken:s,snapshotVersion:n.snapshotVersion}),e.targetIds[t]=o,i.push(e.queryCache.addQueryData(r,o)))}});var a=et();t.documentUpdates.forEach(function(t,s){a=a.add(t),i.push(n.getEntry(r,t).next(function(r){null==r||s.version.equals(He.MIN)||s.version.compareTo(r.version)>=0?n.addEntry(s):o("LocalStore","Ignoring outdated watch update for ",t,". Current version:",r.version," Watch version:",s.version),e.garbageCollector.addPotentialGarbageKey(t)}))});var s=e.queryCache.getLastRemoteSnapshotVersion(),h=t.snapshotVersion;h.equals(He.MIN)||(c(h.compareTo(s)>=0,"Watch stream reverted to previous snapshot?? "+h+" < "+s),i.push(e.queryCache.setLastRemoteSnapshotVersion(r,h)));var l;return Wn.waitFor(i).next(function(){return e.releaseHeldBatchResults(r,n)}).next(function(t){return l=t,n.apply(r)}).next(function(){return e.localDocuments.getDocuments(r,a.unionWith(l))})})},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("Notify local view changes",function(n){for(var r=[],i=0,o=t;i0},t.prototype.releaseBatchResults=function(t,e,n){for(var r=this,i=Wn.resolve(),o=0,a=e;othis.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged"),o=this.mutationQueue[i];return c(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),c(!o.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,Wn.resolve()},t.prototype.getLastStreamToken=function(t){return Wn.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,Wn.resolve()},t.prototype.addMutationBatch=function(t,e,n){c(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;this.nextBatchId++,this.mutationQueue.length>0&&c(this.mutationQueue[this.mutationQueue.length-1].batchId=n?r=n:r++,Wn.resolve(this.getAllLiveMutationBatchesBeforeIndex(r))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new Yn(e,0),i=new Yn(e,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(t){c(e.equals(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);c(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),Wn.resolve(o)},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this,r=e.path,i=r.length+1,o=r;se.isDocumentKey(o)||(o=o.child(""));var a=new Yn(new se(o),0),s=new ln(L);this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!r.isPrefixOf(e)&&(e.length===i&&(s=s.add(t.targetOrBatchId)),!0)},a);var u=[];return s.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&u.push(e)}),Wn.resolve(u)},t.prototype.removeMutationBatches=function(t,e){var n=e.length;c(n>0,"Should not remove mutations when none exist.");var r=e[0].batchId,i=this.mutationQueue.length,o=this.indexOfExistingBatchId(r,"removed");c(this.mutationQueue[o].batchId===r,"Removed batches must exist in the queue");for(var a=1,s=o+1;a=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return c(n.batchId===t,"If found batch must match"),n.isTombstone()?null:n},t}(),Br=function(){function t(){this.queries=new jn(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=He.MIN,this.highestTargetId=0,this.references=new Xn}return t.prototype.start=function(t){return Wn.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.getHighestTargetId=function(){return this.highestTargetId},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,Wn.resolve()},t.prototype.addQueryData=function(t,e){this.queries.set(e.query,e);var n=e.targetId;return n>this.highestTargetId&&(this.highestTargetId=n),Wn.resolve()},t.prototype.removeQueryData=function(t,e){return this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),Wn.resolve()},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return Wn.resolve(n)},t.prototype.addMatchingKeys=function(t,e,n){return this.references.addReferences(e,n),Wn.resolve()},t.prototype.removeMatchingKeys=function(t,e,n){return this.references.removeReferences(e,n),Wn.resolve()},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),Wn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return Wn.resolve(n)},t.prototype.setGarbageCollector=function(t){this.references.setGarbageCollector(t)},t.prototype.containsKey=function(t,e){return this.references.containsKey(t,e)},t}(),Ur=function(){function t(){this.docs=Z()}return t.prototype.addEntry=function(t,e){return this.docs=this.docs.insert(e.key,e),Wn.resolve()},t.prototype.removeEntry=function(t,e){return this.docs=this.docs.remove(e),Wn.resolve()},t.prototype.getEntry=function(t,e){return Wn.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=$(),r=new se(e.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),a=o.key,s=o.value;if(!e.path.isPrefixOf(a.path))break;s instanceof ue&&e.matches(s)&&(n=n.insert(s.key,s))}return Wn.resolve(n)},t}(),Fr=function(){function t(){this.mutationQueues={},this.remoteDocumentCache=new Ur,this.queryCache=new Br,this.started=!1}return t.prototype.start=function(){return c(!this.started,"MemoryPersistence double-started!"),this.started=!0,Promise.resolve()},t.prototype.shutdown=function(){return c(this.started,"MemoryPersistence shutdown without start!"),this.started=!1,Promise.resolve()},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new xr,this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e){return o("MemoryPersistence","Starting transaction:",t),e(new Vr).toPromise()},t}(),Vr=function(){function t(){}return t}(),qr=function(){function t(){this.isEager=!1}return t.prototype.addGarbageSource=function(t){},t.prototype.removeGarbageSource=function(t){},t.prototype.addPotentialGarbageKey=function(t){},t.prototype.collectGarbage=function(t){return Wn.resolve(et())},t}(),jr=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t}(),Kr=function(){function t(t,e,n){this.initialDelayMs=t,this.backoffFactor=e,this.maxDelayMs=n,this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndWait=function(){var t=new jr,e=this.currentBaseMs+this.jitterDelayMs();return this.currentBaseMs>0&&o("ExponentialBackoff","Backing off for "+e+" ms (base delay: "+this.currentBaseMs+" ms)"),setTimeout(function(){t.resolve()},e),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs),t.promise},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}(),Qr=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.Initial=0]="Initial",t[t.Auth=1]="Auth",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff",t[t.Stopped=5]="Stopped"}(Zn||(Zn={}));var Gr,Wr=1e3,Hr=6e4,zr=1.5,Xr=function(){function t(t,e,n,r,i){this.queue=t,this.connection=e,this.credentialsProvider=n,this.stream=null,this.listener=null,this.backoff=new Kr(i||Wr,zr,Hr),this.state=Zn.Initial,this.listener=r}return t.prototype.isStarted=function(){return this.state===Zn.Backoff||this.state===Zn.Auth||this.state===Zn.Open},t.prototype.isOpen=function(){return this.state===Zn.Open},t.prototype.start=function(){if(this.state===Zn.Error)return void this.performBackoff();c(this.state===Zn.Initial,"Already started"),this.auth()},t.prototype.stop=function(){this.state=Zn.Stopped,this.listener=null,null!==this.stream&&(this.stream.close(),this.stream=null)},t.prototype.inhibitBackoff=function(){c(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Zn.Initial,this.backoff.reset()},t.prototype.auth=function(){var t=this;c(this.state===Zn.Initial,"Must be in initial state to auth"),this.state=Zn.Auth,this.credentialsProvider.getToken(!1).then(function(e){t.startStream(e)},function(e){t.queue.schedule(function(){if(t.state!==Zn.Stopped){var n=new zt(Ht.UNKNOWN,"Fetching auth token failed: "+e.message);return t.handleStreamClose(n)}return Promise.resolve()})})},t.prototype.startStream=function(t){var e=this;if(this.state!==Zn.Stopped){c(this.state===Zn.Auth,"Trying to start stream in a non-auth state");var n=function(t){e.queue.schedule(function(){return e.state!==Zn.Stopped?t():Promise.resolve()})};null!==this.listener&&(this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return c(e.state===Zn.Auth,"Expected stream to be in state auth, but was "+e.state),e.state=Zn.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})}))}},t.prototype.performBackoff=function(){var t=this;c(this.state===Zn.Error,"Should only perform backoff in an error case"),this.state=Zn.Backoff,this.backoff.backoffAndWait().then(function(){t.queue.schedule(function(){return t.state===Zn.Stopped?Promise.resolve():(t.state=Zn.Initial,t.start(),c(t.isStarted(),"PersistentStream should have started"),Promise.resolve())})})},t.prototype.handleStreamClose=function(t){return c(this.isStarted(),"Can't handle server close on non-started stream"),o("PersistentStream","close with error: "+t),this.stream=null,this.state=Zn.Error,t&&t.code===Ht.RESOURCE_EXHAUSTED&&(o("PersistentStream","Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()),this.listener.onClose(t)},t}(),Yr=function(t){function e(e,n,r,i,o,a,s){var u=t.call(this,n,r,i,a,s)||this;return u.databaseInfo=e,u.serializer=o,u}return Qr(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.stream.send(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.stream.send(e)},e}(Xr),Jr=function(t){function e(e,n,r,i,o,a,s){var u=t.call(this,n,r,i,a,s)||this;return u.databaseInfo=e,u.serializer=o,u.y=!1,u}return Qr(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.y},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.y=!1,t.prototype.start.call(this)},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(c(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.y){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return c(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.y=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){c(this.isOpen(),"Writing handshake requires an opened stream"),c(!this.y,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.stream.send(t)},e.prototype.writeMutations=function(t){var e=this;c(this.isOpen(),"Writing mutations requires an opened stream"),c(this.y,"Handshake must be complete before writing mutations"),c(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.stream.send(n)},e}(Xr),Zr=function(){function t(t,e,n,r,i,o){this.databaseInfo=t,this.queue=e,this.connection=n,this.credentials=r,this.serializer=i,this.initialBackoffDelay=o}return t.prototype.newPersistentWriteStream=function(t){return new Jr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,t,this.initialBackoffDelay)},t.prototype.newPersistentWatchStream=function(t){return new Yr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,t,this.initialBackoffDelay)},t.prototype.commit=function(t){var e=this,n={writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults)})},t.prototype.lookup=function(t){var e=this,n={documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeRPC("batchGet",n).then(function(n){var r=Z();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var i=[];return t.forEach(function(t){var e=r.get(t);c(!!e,"Missing entity in write response for "+t),i.push(e)}),i})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invoke(t,e,r)})},t}(),$r=function(){function t(t){this.datastore=t,this.readVersions=tt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e=t.version;t instanceof ce&&(e=He.forDeletedDoc());var n=this.readVersions.get(t.key);if(null!==n){if(!e.equals(n))throw new zt(Ht.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){return e.recordVersion(t)}),t})},t.prototype.write=function(t){if(this.committed)throw new zt(Ht.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?nn.updateTime(e):nn.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.equals(He.forDeletedDoc()))throw new zt(Ht.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?nn.updateTime(e):nn.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new un(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,He.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}(),ti=function(){function t(t,e,n,r,i){this.databaseInfo=t,this.asyncQueue=e,this.localStore=n,this.datastore=r,this.onlineStateHandler=i,this.pendingWrites=[],this.lastBatchSeen=or,this.listenTargets={},this.pendingTargetResponses={},this.accumulatedWatchChanges=[],this.watchStream=null,this.writeStream=null,this.watchStreamOnlineState=Pn.Unknown,this.watchStreamFailures=0}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.setOnlineStateToHealthy=function(){this.updateAndBroadcastOnlineState(Pn.Healthy)},t.prototype.setOnlineStateToUnknown=function(){this.watchStreamFailures=0,this.updateAndBroadcastOnlineState(Pn.Unknown)},t.prototype.updateOnlineStateAfterFailure=function(){this.watchStreamOnlineState===Pn.Healthy?this.setOnlineStateToUnknown():++this.watchStreamFailures>=2&&this.updateAndBroadcastOnlineState(Pn.Failed)},t.prototype.updateAndBroadcastOnlineState=function(t){var e=this.watchStreamOnlineState!==t;this.watchStreamOnlineState=t,e&&this.onlineStateHandler(t)},t.prototype.isNetworkEnabled=function(){return c(null==this.watchStream==(null==this.writeStream),"WatchStream and WriteStream should both be null or non-null"),null!=this.watchStream},t.prototype.enableNetwork=function(){var t=this;return c(null==this.watchStream,"enableNetwork() called with non-null watchStream."),c(null==this.writeStream,"enableNetwork() called with non-null writeStream."),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)}),this.localStore.getLastStreamToken().then(function(e){return t.writeStream.lastStreamToken=e,t.shouldStartWatchStream()&&t.startWatchStream(),t.updateAndBroadcastOnlineState(Pn.Unknown),t.fillWritePipeline()})},t.prototype.disableNetwork=function(){return this.updateAndBroadcastOnlineState(Pn.Failed),this.watchStream.stop(),this.writeStream.stop(),this.cleanUpWatchStreamState(),this.cleanUpWriteStreamState(),this.writeStream=null,this.watchStream=null,Promise.resolve()},t.prototype.shutdown=function(){return o("RemoteStore","RemoteStore shutting down."),this.disableNetwork(),Promise.resolve(void 0)},t.prototype.listen=function(t){c(!f(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){c(f(this.listenTargets,t),"unlisten called without assigned target ID!"),this.listenTargets[t],delete this.listenTargets[t],this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendUnwatchRequest(t)},t.prototype.sendWatchRequest=function(t){this.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.recordPendingTargetRequest=function(t){this.pendingTargetResponses[t]=(this.pendingTargetResponses[t]||0)+1},t.prototype.startWatchStream=function(){c(this.shouldStartWatchStream(),"startWriteStream() called when shouldStartWatchStream() is false."),this.watchStream.start()},t.prototype.shouldStartWatchStream=function(){return this.isNetworkEnabled()&&!this.watchStream.isStarted()&&!m(this.listenTargets)},t.prototype.cleanUpWatchStreamState=function(){this.accumulatedWatchChanges=[],this.pendingTargetResponses={}},t.prototype.onWatchStreamOpen=function(){var t=this;return d(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),Promise.resolve()},t.prototype.onWatchStreamClose=function(t){return c(this.isNetworkEnabled(),"onWatchStreamClose() should only be called when the network is enabled"),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.updateOnlineStateAfterFailure(),this.startWatchStream()):this.setOnlineStateToUnknown(),Promise.resolve()},t.prototype.onWatchStreamChange=function(t,e){if(this.setOnlineStateToHealthy(),t instanceof En&&t.state===gn.Removed&&t.cause)return this.handleTargetError(t);if(this.accumulatedWatchChanges.push(t),!e.equals(He.MIN)&&e.compareTo(this.localStore.getLastRemoteSnapshotVersion())>=0){var n=this.accumulatedWatchChanges;return this.accumulatedWatchChanges=[],this.handleWatchChangeBatch(e,n)}return Promise.resolve()},t.prototype.handleWatchChangeBatch=function(t,e){var n=this,r=new Sn(t,this.listenTargets,this.pendingTargetResponses);r.addChanges(e);var i=r.createRemoteEvent();this.pendingTargetResponses=r.pendingTargetResponses;var o=[];return d(r.existenceFilters,function(e,r){var a=n.listenTargets[e];if(a){var s=a.query;if(s.isDocumentQuery())if(0===r.count){var u=new se(s.path),h=new ce(u,t);i.addDocumentUpdate(h)}else c(1===r.count,"Single document existence filter with count: "+r.count);else{var l=n.localStore.remoteDocumentKeys(e).then(function(t){if(i.targetChanges[e]){var o=i.targetChanges[e].mapping;null!==o&&(o instanceof wn?t=o.applyToKeySet(t):(c(o instanceof bn,"Expected either reset or update mapping but got something else: "+o),t=o.documents))}if(t.size!==r.count){i.handleExistenceFilterMismatch(e);var u=new Xe(s,e,a.purpose);n.listenTargets[e]=u,n.sendUnwatchRequest(e);var h=new Xe(s,e,me.ExistenceFilterMismatch);n.sendWatchRequest(h)}});o.push(l)}}}),Promise.all(o).then(function(){return d(i.targetChanges,function(t,e){if(e.resumeToken.length>0){var r=n.listenTargets[t];r&&(n.listenTargets[t]=r.update({resumeToken:e.resumeToken,snapshotVersion:e.snapshotVersion}))}}),n.syncEngine.applyRemoteEvent(i)})},t.prototype.handleTargetError=function(t){var e=this;c(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return f(e.listenTargets,t)?(delete e.listenTargets[t],e.syncEngine.rejectListen(t,n)):Promise.resolve()})}),r},t.prototype.cleanUpWriteStreamState=function(){this.lastBatchSeen=or,this.pendingWrites=[]},t.prototype.fillWritePipeline=function(){var t=this;return this.canWriteMutations()?this.localStore.nextMutationBatch(this.lastBatchSeen).then(function(e){return null===e?Promise.resolve():(t.commit(e),t.fillWritePipeline())}):Promise.resolve()},t.prototype.canWriteMutations=function(){return this.isNetworkEnabled()&&this.pendingWrites.length<10},t.prototype.outstandingWrites=function(){return this.pendingWrites.length},t.prototype.commit=function(t){c(this.canWriteMutations(),"commit called when batches can't be written"),this.lastBatchSeen=t.batchId,this.pendingWrites.push(t),this.shouldStartWriteStream()?this.startWriteStream():this.isNetworkEnabled()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.isNetworkEnabled()&&!this.writeStream.isStarted()&&this.pendingWrites.length>0},t.prototype.startWriteStream=function(){c(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return this.writeStream.writeHandshake(),Promise.resolve()},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.pendingWrites;e0,"Got result for empty pending writes");var r=this.pendingWrites.shift(),i=sr.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){var e=this;if(c(this.isNetworkEnabled(),"onWriteStreamClose() should only be called when the network is enabled"),this.pendingWrites.length>0){c(!!t,"We have pending writes, but the write stream closed without an error");var n=void 0;return n=this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t),n.then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})}return Promise.resolve()},t.prototype.handleHandshakeError=function(t){return H(t.code)||t.code===Ht.ABORTED?(o("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=h(),this.localStore.setLastStreamToken(h())):Promise.resolve()},t.prototype.handleWriteError=function(t){var e=this;if(H(t.code)){var n=this.pendingWrites.shift();return this.writeStream.inhibitBackoff(),this.syncEngine.rejectFailedWrite(n.batchId,t).then(function(){return e.fillWritePipeline()})}return Promise.resolve()},t.prototype.createTransaction=function(){return new $r(this.datastore)},t.prototype.handleUserChange=function(t){return o("RemoteStore","RemoteStore changing users: uid=",t.uid),this.disableNetwork(),this.enableNetwork()},t}(),ei=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r}return t.prototype.start=function(t){var e=this,n=new jr,r=new jr,i=!1;return this.credentials.setUserChangeListener(function(o){i?e.asyncQueue.schedule(function(){return e.handleUserChange(o)}):(i=!0,e.initializePersistence(t,r).then(function(){return e.initializeRest(o)}).then(n.resolve,n.reject))}),this.asyncQueue.schedule(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.enableNetwork()})},t.prototype.initializePersistence=function(t,e){var n=this;return t?this.startIndexedDbPersistence().then(e.resolve).catch(function(t){return e.reject(t),n.canFallback(t)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),n.startMemoryPersistence()):Promise.reject(t)}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t.code===Ht.FAILED_PRECONDITION||t.code===Ht.UNIMPLEMENTED},t.prototype.startIndexedDbPersistence=function(){this.garbageCollector=new qr;var t=Mr.buildStoragePrefix(this.databaseInfo),e=new Cn(this.databaseInfo.databaseId,{useProto3Json:!0});return this.persistence=new Mr(t,e),this.persistence.start()},t.prototype.startMemoryPersistence=function(){return this.garbageCollector=new Hn,this.persistence=new Fr,this.persistence.start()},t.prototype.initializeRest=function(t){var e=this;return this.platform.loadConnection(this.databaseInfo).then(function(n){e.localStore=new Lr(e.persistence,t,e.garbageCollector);var r=e.platform.newSerializer(e.databaseInfo.databaseId),i=new Zr(e.databaseInfo,e.asyncQueue,n,e.credentials,r),o=function(t){e.eventMgr.onOnlineStateChanged(t)};return e.remoteStore=new ti(e.databaseInfo,e.asyncQueue,e.localStore,i,o),e.syncEngine=new ir(e.localStore,e.remoteStore,t),e.remoteStore.syncEngine=e.syncEngine,e.eventMgr=new Qn(e.syncEngine),e.localStore.start()}).then(function(){return e.remoteStore.start()})},t.prototype.handleUserChange=function(t){return this.asyncQueue.verifyOperationInProgress(),o("FirestoreClient","User Changed: "+t.uid),this.syncEngine.handleUserChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.disableNetwork()})},t.prototype.shutdown=function(){var t=this;return this.asyncQueue.schedule(function(){return t.credentials.removeUserChangeListener(),t.remoteStore.shutdown()}).then(function(){return t.persistence.shutdown()})},t.prototype.listen=function(t,e,n){var r=this,i=new Gn(t,e,n);return this.asyncQueue.schedule(function(){return r.eventMgr.listen(i)}),i},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.schedule(function(){return e.eventMgr.unlisten(t)})},t.prototype.write=function(t){var e=this,n=new jr;return this.asyncQueue.schedule(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.schedule(function(){return Promise.resolve()}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),ni=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),ri=function(){function t(){this.tail=Promise.resolve(),this.delayedOpCount=0,this.operationInProgress=!1}return t.prototype.schedule=function(t,e){var n=this;if(this.failure&&u("AsyncQueue is already failed: "+this.failure.message),(e||0)>0){this.delayedOpCount++;var r=new jr;return setTimeout(function(){n.scheduleInternal(function(){return t().then(function(t){r.resolve(t)})}),n.delayedOpCount--},e),r.promise}return this.scheduleInternal(t)},t.prototype.scheduleInternal=function(t){var e=this;return this.tail=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){throw e.failure=t,e.operationInProgress=!1,a("INTERNAL UNHANDLED ERROR: ",t.stack||t.message),t}).then(function(){e.operationInProgress=!1})}),this.tail},t.prototype.verifyOperationInProgress=function(){c(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return c(0===this.delayedOpCount,"draining doesn't handle delayed ops."),this.schedule(function(){return Promise.resolve(void 0)})},t}(),ii=function(){function t(t){this.uid=t}return t.prototype.isUnauthenticated=function(){return null==this.uid},t.prototype.toKey=function(){return this.isUnauthenticated()?"anonymous-user":"uid:"+this.uid},t.prototype.equals=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),oi=function(){function t(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}return t}(),ai=function(){function t(){this.userListener=null}return t.prototype.getToken=function(t){return Promise.resolve(null)},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,t(ii.UNAUTHENTICATED)},t.prototype.removeUserChangeListener=function(){c(null!==this.userListener,"removeUserChangeListener() when no listener registered"),this.userListener=null},t}(),si=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.userCounter=0,this.userListener=null,this.tokenListener=function(){var t=e.getUser();e.currentUser&&t.equals(e.currentUser)||(e.currentUser=t,e.userCounter++,e.userListener&&e.userListener(e.currentUser))},this.userCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(t){var e=this;c(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.userCounter;return this.app.INTERNAL.getToken(t).then(function(t){if(e.userCounter!==n)throw new zt(Ht.ABORTED,"getToken aborted due to uid change.");return t?(c("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new oi(t.accessToken,e.currentUser)):null})},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeUserChangeListener=function(){c(null!=this.tokenListener,"removeUserChangeListener() called twice"),c(null!==this.userListener,"removeUserChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.userListener=null},t.prototype.getUser=function(){"function"!=typeof this.app.INTERNAL.getUid&&u("This version of the Firestore SDK requires at least version 3.7.0 of firebase.js.");var t=this.app.INTERNAL.getUid();return c(null===t||"string"==typeof t,"Received invalid UID: "+t),new ii(t)},t}(),ui=function(){function t(t){this.authClient=t}return t.prototype.getToken=function(t){var e=this;return new Promise(function(t,n){e.authClient.getAccessToken(function(e,r){e?n(e):t(new oi(r,ii.GOOGLE_CREDENTIALS))})})},t.prototype.setUserChangeListener=function(t){t(ii.GOOGLE_CREDENTIALS)},t.prototype.removeUserChangeListener=function(){},t}(),ci=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=ii.FIRST_PARTY,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),hi=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(t){return Promise.resolve(new ci(this.gapi,this.sessionIndex))},t.prototype.setUserChangeListener=function(t){t(ii.FIRST_PARTY)},t.prototype.removeUserChangeListener=function(){},t}(),li=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),fi=function(){function t(){}return t.delete=function(){return pi.instance},t.serverTimestamp=function(){return di.instance},t}(),pi=function(t){function e(){return t.call(this)||this}return li(e,t),e.instance=new e,e}(fi),di=function(t){function e(){return t.call(this)||this}return li(e,t),e.instance=new e,e}(fi),yi=l(fi,"Use FieldValue.() instead."),mi=/^__.*__$/,gi=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new an(t,this.data,this.fieldMask,e)):n.push(new on(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}(),vi=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new an(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}();!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.QueryValue=3]="QueryValue"}(Gr||(Gr={}));var bi=function(){function t(t,e,n,r,i,o){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===i&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=i||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path+")";return new zt(Ht.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() can only be used with update() and set() with {merge:true}")}if(t instanceof di){if(!kt(e.dataSource))throw e.createError("FieldValue.serverTimestamp() can only be used with set() and update()");if(null===e.path)throw e.createError("FieldValue.serverTimestamp() is not currently supported inside arrays");return e.fieldTransforms.push(new $e(e.path,Ze.instance)),null}return u("Unknown FieldValue type: "+t)}throw e.createError("Unsupported field value: "+A(t))},t}(),Ti=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ei="firestore.googleapis.com",Si=!0,Ni=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new zt(Ht.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Ei,this.ssl=Si}else S("settings","string","host",t.host),this.host=t.host,N("settings","boolean","ssl",t.ssl),this.ssl=p(t.ssl,Si);O("settings",t,["host","ssl","credentials"]),N("settings","object","credentials",t.credentials),this.credentials=t.credentials}return t.prototype.equals=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials},t}(),Di=function(){function t(){}return t}(),Ci=function(){function t(e){var n=this;this.INTERNAL={delete:function(){return n.k?n.k.shutdown():Promise.resolve()},disableNetwork:function(){return n.k.disableNetwork()},enableNetwork:function(){return n.k.enableNetwork()}};var r=new Di;if("object"==typeof e.options){var i=e;r.firebaseApp=i,r.databaseId=t.databaseIdFromApp(i),r.persistenceKey=r.firebaseApp.name,r.credentials=new si(i)}else{var o=e;if(!o.projectId)throw new zt(Ht.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new ee(o.projectId,o.database),r.persistenceKey="[DEFAULT]",r.credentials=new ai}r.settings=new Ni({}),this._=r,this._databaseId=r.databaseId}return t.prototype.settings=function(t){if(v("Firestore.settings",arguments,1),T("Firestore.settings","object",1,t),f(t,"persistence"))throw new zt(Ht.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Ni(t);if(this.k&&!this._.settings.equals(e))throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this._.settings=e,void 0!==e.credentials&&(this._.credentials=Dt(e.credentials))},t.prototype.enablePersistence=function(){if(this.k)throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");return this.configureClient(!0)},t.prototype.ensureClientConfigured=function(){return this.k||this.configureClient(!1),this.k},t.prototype.configureClient=function(t){var e=this;c(!!this._.settings.host,"FirestoreSettings.host cannot be falsey"),c(!this.k,"configureClient() called multiple times");var n=new $t(this._.databaseId,this._.persistenceKey,this._.settings.host,this._.settings.ssl),r=function(t){if(t instanceof Ri){var n=e._.databaseId,r=t.firestore._.databaseId;if(!r.equals(n))throw new zt(Ht.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new wi(e._.databaseId,t.x)}return t};return this._dataConverter=new Ii(r),this.k=new ei(Gt.getPlatform(),n,this._.credentials,new ri),this.k.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!f(e,"projectId")){if(f(e,"firestoreId"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreId" is now specified as "projectId" in firebase.initializeApp.');throw new zt(Ht.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')}if(f(e,"firestoreOptions"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreOptions" values are now specified with Firestore.settings()');var n=e.projectId;if(!n||"string"!=typeof n)throw new zt(Ht.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new ee(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this._.firebaseApp)throw new zt(Ht.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("Firestore.collection",arguments,1),T("Firestore.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new Pi(ie.fromString(t),this)},t.prototype.doc=function(t){if(v("Firestore.doc",arguments,1),T("Firestore.doc","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),Ri.forPath(ie.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return v("Firestore.runTransaction",arguments,1),T("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Ai(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new ki(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(r()){case qt.DEBUG:return"debug";case qt.ERROR:return"error";case qt.SILENT:return"silent";default:return u("Unknown log level: "+r())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(v("Firestore.setLogLevel",arguments,1),T("Firestore.setLogLevel","string",1,t),t){case"debug":i(qt.DEBUG);break;case"error":i(qt.ERROR);break;case"silent":i(qt.SILENT);break;default:throw new zt(Ht.INVALID_ARGUMENT,"Invalid log level: "+t)}},t}(),Ai=function(){function t(t,e){this.q=t,this.Q=e}return t.prototype.get=function(t){var e=this;v("Transaction.get",arguments,1);var n=xt("Transaction.get",t,this.q);return this.Q.lookup([n.x]).then(function(t){if(!t||1!==t.length)return u("Mismatch in docs returned from document lookup.");var r=t[0];return r instanceof ce?new Oi(e.q,n.x,null,!1):new Oi(e.q,n.x,r,!1)})},t.prototype.set=function(t,e,n){w("Transaction.set",arguments,2,3);var r=xt("Transaction.set",t,this.q);n=Lt("Transaction.set",n);var i=n.merge?this.q._dataConverter.parseMergeData("Transaction.set",e):this.q._dataConverter.parseSetData("Transaction.set",e);return this.Q.set(r.x,i),this},t.prototype.update=function(t,e,n){for(var r=[],i=3;i0?this.q.ensureClientConfigured().write(this.z):Promise.resolve()},t.prototype.verifyNotCommitted=function(){if(this.tt)throw new zt(Ht.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Ri=function(){function t(t,e){this.x=t,this.firestore=e,this.k=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new se(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this.x.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new Pi(this.x.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.x.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("DocumentReference.collection",arguments,1),T("DocumentReference.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=ie.fromString(t);return new Pi(this.x.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw M("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this.x.equals(e.x)},t.prototype.set=function(t,e){w("DocumentReference.set",arguments,1,2),e=Lt("DocumentReference.set",e);var n=e.merge?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this.k.write(n.toMutations(this.x,nn.NONE))},t.prototype.update=function(t,e){for(var n=[],r=2;r0)throw new zt(Ht.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new zt(Ht.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,i.et,r)}var o=[e].concat(n);return this.boundFromFields(t,o,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this.rt.orderBy;ir.length)throw new zt(Ht.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],o=0;o, or >=) must be on the same field. But you have inequality filters on '"+e+"' and '"+t.field+"'");var n=this.rt.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}},t.prototype.validateNewOrderBy=function(t){if(null===this.rt.getFirstOrderByField()){var e=this.rt.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.equals(t))throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t+"' and so you must also use '"+t+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e+"' instead.")},t}(),_i=function(){function t(t,e,n){this.q=t,this.it=e,this.ot=n,this._cachedChanges=null,this.metadata={fromCache:n.fromCache,hasPendingWrites:n.hasPendingWrites}}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this.ot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.ot.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;w("QuerySnapshot.forEach",arguments,1,2),T("QuerySnapshot.forEach","function",1,t),this.ot.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new Mi(this.it,this.q)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"docChanges",{get:function(){return this._cachedChanges||(this._cachedChanges=Bt(this.q,this.ot)),this._cachedChanges},enumerable:!0,configurable:!0}),t.prototype.convertToDocumentImpl=function(t){return new Oi(this.q,t.key,t,this.metadata.fromCache)},t}(),Pi=function(t){function e(e,n){var r=t.call(this,Le.atPath(e),n)||this;if(e.length%2!=1)throw new zt(Ht.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return Ti(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.rt.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.rt.path.popLast();return t.isEmpty()?null:new Ri(new se(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.rt.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(w("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=Xt.newId()),T("CollectionReference.doc","string",1,t),""===t)throw new zt(Ht.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=ie.fromString(t);return Ri.forPath(this.rt.path.child(e),this.firestore)},e.prototype.add=function(t){v("CollectionReference.add",arguments,1),T("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(Mi),Li=l(Ci,"Use firebase.firestore() instead."),xi=l(Ai,"Use firebase.firestore().runTransaction() instead."),Bi=l(ki,"Use firebase.firestore().batch() instead."),Ui=l(Ri,"Use firebase.firestore().doc() instead."),Fi=l(Oi),Vi=l(Mi),qi=l(_i),ji=l(Pi,"Use firebase.firestore().collection() instead."),Ki={Firestore:Li,GeoPoint:Zt,Blob:Jt,Transaction:xi,WriteBatch:Bi,DocumentReference:Ui,DocumentSnapshot:Fi,Query:Vi,QuerySnapshot:qi,CollectionReference:ji,FieldPath:Ln,FieldValue:yi,setLogLevel:Ci.setLogLevel};e.registerFirestore=Vt,Vt(jt.default)},115:function(module,exports,__webpack_require__){(function(){function l(t){return"string"==typeof t}function aa(){}function ba(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function n(t){return"array"==ba(t)}function ca(t){var e=ba(t);return"array"==e||"object"==e&&"number"==typeof t.length}function da(t){return"function"==ba(t)}function p(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}function fa(t,e,n){return t.call.apply(t.bind,arguments)}function ha(t,e,n){if(!t)throw Error();if(2e?1:0}function na(t,e){e.unshift(t),ja.call(this,ka.apply(null,e)),e.shift()}function oa(t,e){throw new na("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this),this.i=this.i,this.v=this.v}function ua(t){t:{for(var e=va,n=t.length,r=l(t)?t.split(""):t,i=0;ie?null:l(t)?t.charAt(e):t[e]}function wa(t){if(!n(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function xa(t){return Array.prototype.concat.apply([],arguments)}function ya(t){var e=t.length;if(0r.keyCode||void 0!=r.returnValue)){t:{var i=!1;if(0==r.keyCode)try{r.keyCode=-1;break t}catch(t){i=!0}(i||void 0==r.returnValue)&&(r.returnValue=!0)}for(r=[],i=e.a;i;i=i.parentNode)r.push(i);for(t=t.type,i=r.length-1;0<=i;i--){e.a=r[i];var o=yb(r[i],t,!0,e);n=n&&o}for(i=0;is.length)){var u=s[1];if(n(u)&&!(1>u.length)){var c=u[0];if("noop"!=c&&"stop"!=c&&"close"!=c)for(var h=1;he.length?Kc:(e=e.substr(r,n),t.C=r+n,e))}function Pc(e){e.T=t()+e.P,Xc(e,e.P)}function Xc(t,e){if(null!=t.o)throw Error("WatchDog timer not null");t.o=xc(r(t.eb,t),e)}function Rc(t){t.o&&(k.clearTimeout(t.o),t.o=null)}function Vc(t){t.m.Ka()||t.s||t.m.wa(t)}function Uc(t){Rc(t);var e=t.G;e&&"function"==typeof e.Y&&e.Y(),t.G=null,Yb(t.F),cc(t.M),t.a&&(e=t.a,t.a=null,e.abort(),e.Y())}function Tc(t,e){try{t.m.Na(t,e),uc()}catch(e){sc(t.b,e,"Error in httprequest callback")}}function Yc(t){if(t.A&&"function"==typeof t.A)return t.A();if(l(t))return t.split("");if(ca(t)){for(var e=[],n=t.length,r=0;r2*t.c&&$c(t),!0)}function $c(t){if(t.c!=t.a.length){for(var e=0,n=0;ee)throw Error("Bad port number "+e);t.i=e}else t.i=null}function hd(t,e,n){e instanceof kd?(t.c=e,qd(t.c,t.h)):(n||(e=ld(e,rd)),t.c=new kd(e,0,t.h))}function R(t,e,n){t.c.set(e,n)}function Qc(t,e,r){n(r)||(r=[r+""]),sd(t.c,e,r)}function Mc(e){return R(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36)),e}function td(t){return t instanceof Q?M(t):new Q(t,void 0)}function ud(t,e,n,r){var i=new Q(null,void 0);return t&&ed(i,t),e&&fd(i,e),n&&gd(i,n),r&&(i.a=r),i}function jd(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function ld(t,e,n){return l(t)?(t=encodeURI(t).replace(e,vd),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function vd(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function kd(t,e,n){this.b=this.a=null,this.c=t||null,this.f=!!n}function S(t){t.a||(t.a=new O,t.b=0,t.c&&dd(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function xd(t,e){S(t),e=wd(t,e),P(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,bd(t.a,e))}function yd(t,e){return S(t),e=wd(t,e),P(t.a.b,e)}function sd(t,e,n){xd(t,e),0=t.c}function Td(t,e){return t.b?t.b==e:!!t.a&&t.a.contains(e)}function Rd(t,e){t.a?t.a.add(e):t.b=e}function Ud(t,e){this.a=t,this.b=e}function Vd(t,e){this.a=t,this.b=e}function Wd(){this.a=new Vd}function Xd(t,e,n){var r=n||"";try{Zc(t,function(t,n){var i=t;p(t)&&(i=Eb(t)),e.push(r+n+"="+encodeURIComponent(i))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}}function Yd(t,e){var n=new qc;I(n,"TestLoadImage: loading "+t);var r=new Image;r.onload=ia(Zd,n,r,"TestLoadImage: loaded",!0,e),r.onerror=ia(Zd,n,r,"TestLoadImage: error",!1,e),r.onabort=ia(Zd,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=ia(Zd,n,r,"TestLoadImage: timeout",!1,e),k.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}function Zd(t,e,n,r,i){try{I(t,n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(e){sc(t,e)}}function U(t){B.call(this),this.headers=new O,this.G=t||null,this.f=!1,this.F=this.a=null,this.M=this.s="",this.j=0,this.g="",this.h=this.I=this.o=this.H=!1,this.l=0,this.B=null,this.N=$d,this.C=this.m=!1}function ee(t){return z&&Ua(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}function va(t){return"content-type"==t.toLowerCase()}function ce(t,e){t.f=!1,t.a&&(t.h=!0,t.a.abort(),t.h=!1),t.g=e,t.j=5,fe(t),ge(t)}function fe(t){t.H||(t.H=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function he(t){if(t.f&&void 0!==goog)if(t.F[1]&&4==N(t)&&2==t.V())H(t.b,V(t,"Local request error detected and ignored"));else if(t.o&&4==N(t))Zb(t.Ma,0,t);else if(t.dispatchEvent("readystatechange"),4==N(t)){H(t.b,V(t,"Request complete")),t.f=!1;try{var e=t.V();t:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var n=!0;break t;default:n=!1}var r;if(!(r=n)){var i;if(i=0===e){var o=(t.s+"").match(cd)[1]||null;if(!o&&k.self&&k.self.location){var a=k.self.location.protocol;o=a.substr(0,a.length-1)}i=!ae.test(o?o.toLowerCase():"")}r=i}r?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.j=6,t.g=t.Ha()+" ["+t.V()+"]",fe(t))}finally{ge(t)}}}function ge(t,e){if(t.a){de(t);var n=t.a,r=t.F[0]?aa:null;t.a=null,t.F=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&F(t,"Problem encountered resetting onreadystatechange: "+e.message)}}}function de(t){t.a&&t.C&&(t.a.ontimeout=null),"number"==typeof t.B&&(k.clearTimeout(t.B),t.B=null)}function N(t){return t.a?t.a.readyState:0}function V(t,e){return e+" ["+t.M+" "+t.s+" "+t.V()+"]"}function ie(t){var e="";return Ba(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}function je(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=ie(n),l(t)){if(e=encodeURIComponent(e+""),n=null!=n?"="+encodeURIComponent(n+""):"",e+=n){if(n=t.indexOf("#"),0>n&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var i=""}else i=t.substring(r+1,n);t=[t.substr(0,r),i,t.substr(n)],n=t[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return R(t,e,n),t}function ke(t,e,n){this.za=e||0,this.Ba=0,this.h=[],this.l=[],this.a=new qc,this.J=n||new Md,this.ia=this.ya=this.H=this.ja=this.b=this.N=this.j=this.ha=this.f=this.P=this.i=null,this.Va=this.I=0,this.ka=this.C=this.s=this.m=this.o=this.c=null,this.v=this.Aa=this.S=-1,this.ga=this.B=this.G=0,this.T=t&&t.supportsCrossDomainXhr||!1,this.M="",this.g=new Od(t&&t.concurrentRequestLimit),this.la=new Wd,this.F=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,this.Ua=t&&t.fastHandshake||!1}function le(e){if(I(e.a,"disconnect()"),me(e),3==e.D){var n=e.I++,r=M(e.H);R(r,"SID",e.M),R(r,"RID",n),R(r,"TYPE","terminate"),ne(e,r),n=new L(e,e.a,0,n,void 0),n.I=2,n.l=Mc(M(r)),r=!1,k.navigator&&k.navigator.sendBeacon&&(r=k.navigator.sendBeacon(""+n.l,"")),r||((new Image).src=n.l),n.H=t(),Pc(n)}oe(e)}function me(t){t.C&&(t.C.abort(),t.C=null),t.b&&(t.b.cancel(),t.b=null),t.m&&(k.clearTimeout(t.m),t.m=null),pe(t),t.g.cancel(),t.o&&(k.clearTimeout(t.o),t.o=null)}function qe(t,e){if(1e3==t.h.length){var n="Already have 1000 queued maps upon queueing "+Eb(e),r=t.a.a;r&&F(r,n)}t.h.push(new Ud(t.Va++,e)),3==t.D&&re(t)}function re(t){Sd(t.g)||t.o||(t.o=xc(r(t.Pa,t),0),t.G=0)}function te(t,e){if(e){t.h=t.l.concat(t.h),t.l.length=0;var n=t.I-1}else n=t.I++;e=se(t);var r=M(t.H);R(r,"SID",t.M),R(r,"RID",n),R(r,"AID",t.S),ne(t,r),t.f&&t.i&&je(r,t.f,t.i),n=new L(t,t.a,0,n,t.G+1),null===t.f&&(n.h=t.i),n.setTimeout(Math.round(1e4)+Math.round(1e4*Math.random())),Rd(t.g,n),Lc(n,r,e)}function ne(t,e){t.c&&Zc({},function(t,n){R(e,n,t)})}function se(t){var e=Math.min(t.h.length,1e3),n=t.c?r(t.c.Wa,t.c,t):null,i=t.h,o=["count="+e];if(0this.c)throw Error(Je);this.a=new Ge,this.b=new T,this.g=null,this.aa()}function Ke(t){if("function"==typeof t.Y)t.Y();else for(var e in t)t[e]=null}function Le(t,e){this.a=t,this.b=e}function Me(t){if(this.a=[],t)t:{if(t instanceof Me){var e=t.O();if(t=t.A(),0>=this.u()){for(var n=this.a,r=0;r>1,t[r].a>n.a);)t[e]=t[r],e=r;t[e]=n}function Oe(){Me.call(this)}function Y(t,e){this.f=new Oe,Ie.call(this,t,e)}function Z(t,e,n,r){this.l=t,this.j=!!r,Y.call(this,e,n)}var g,goog=goog||{},k=this,q="closure_uid_"+(1e9*Math.random()>>>0),ea=0,t=Date.now||function(){return+new Date};u(ja,Error),ja.prototype.name="CustomError";var la=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};u(na,ja),na.prototype.name="AssertionError";var qa=0,ra={};w.prototype.i=!1,w.prototype.Y=function(){if(!this.i&&(this.i=!0,this.w(),0!=qa)){var t=this[q]||(this[q]=++ea);delete ra[t]}},w.prototype.w=function(){if(this.v)for(;this.v.length;)this.v.shift()()};var sa=Array.prototype.indexOf?function(t,e,n){return Array.prototype.indexOf.call(t,e,n)}:function(t,e,n){if(n=null==n?0:0>n?Math.max(0,t.length+n):n,l(t))return l(e)&&1==e.length?t.indexOf(e,n):-1;for(;nparseFloat(Qa)){Pa=Ta+"";break t}}Pa=Qa}var Ja={},Va,Wa=k.document;Va=Wa&&z?Oa()||("CSS1Compat"==Wa.compatMode?parseInt(Pa,10):5):void 0;var Xa=Object.freeze||function(t){return t},Ya=!z||9<=+Va,Za=z&&!Ua("9"),$a=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return k.addEventListener("test",aa,e),k.removeEventListener("test",aa,e),t}();A.prototype.b=function(){this.Qa=!1},u(ab,A);var bb=Xa({2:"touch",3:"pen",4:"mouse"});ab.prototype.b=function(){ab.L.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,Za)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var cb="closure_listenable_"+(1e6*Math.random()|0),eb=0;hb.prototype.add=function(t,e,n,r,i){var o=""+t;(t=this.a[o])||(t=this.a[o]=[],this.b++);var a=ib(t,e,r,i);return-1>>0);u(B,w),B.prototype[cb]=!0,g=B.prototype,g.addEventListener=function(t,e,n,r){ob(this,t,e,n,r)},g.removeEventListener=function(t,e,n,r){wb(this,t,e,n,r)},g.dispatchEvent=function(t){var e,n=this.J;if(n)for(e=[];n;n=n.J)e.push(n);n=this.P;var r=t.type||t;if(l(t))t=new A(t,n);else if(t instanceof A)t.target=t.target||n;else{var i=t;t=new A(r,n),Ga(t,i)}if(i=!0,e)for(var o=e.length-1;0<=o;o--){var a=t.a=e[o];i=Bb(a,r,!0,t)&&i}if(a=t.a=n,i=Bb(a,r,!0,t)&&i,i=Bb(a,r,!1,t)&&i,e)for(o=0;o=lc(this).value)for(da(e)&&(e=e()),t=new dc(t,e+"",this.f),n&&(t.a=n),n="log:"+t.b,(t=k.console)&&t.timeStamp&&t.timeStamp(n),(t=k.msWriteProfilerMark)&&t(n),n=this;n;)n=n.a};var mc={},nc=null,J=new B;u(tc,A),u(vc,A),u(wc,A);var yc={NO_ERROR:0,kb:1,rb:2,qb:3,nb:4,pb:5,sb:6,Sa:7,TIMEOUT:8,vb:9},zc={mb:"complete",zb:"success",Ta:"error",Sa:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",tb:"incrementaldata",wb:"progress",ob:"downloadprogress",Ab:"uploadprogress"};Ac.prototype.a=null;var Dc;u(Ec,Ac),Dc=new Ec;var Gc=45e3,Hc=250,Jc={},Kc={};g=L.prototype,g.setTimeout=function(t){this.P=t},g.gb=function(t){t=t.target;var e=this.G;e&&3==N(t)?(I(this.b,"Throttling readystatechange."),e.Ya()):this.Ra(t)},g.Ra=function(t){try{if(t==this.a){var e=N(this.a),n=this.a.Ga();if(!(3>e||3==e&&!Ka&&!this.a.U())){this.s||4!=e||7==n||uc(),Rc(this);var r=this.a.V();this.v=r;var i=this.a.U();if(i||I(this.b,"No response text for uri "+this.g+" status "+r),this.c=200==r,I(this.b,"XMLHTTP RESP ("+this.f+") [ attempt "+this.S+"]: "+this.j+"\n"+this.g+"\n"+e+" "+r),this.c)this.J?(Sc(this,e,i),Ka&&this.c&&3==e&&(this.M.$(this.F,"tick",this.fb),this.F.start())):(rc(this.b,this.f,i,null),Tc(this,i)),4==e&&Uc(this),this.c&&!this.s&&(4==e?this.m.wa(this):(this.c=!1,Pc(this)));else{if(400==r&&0e&&this.ka&&0==this.B&&!this.s&&(this.s=xc(r(this.ab,this),6e3)));else I(this.a,"Bad POST response data returned"),W(this,11)}else if(this.b==t&&pe(this),!/^[\s\xa0]*$/.test(e))for(e=i=this.la.a.parse(e),i=0;ie-this.g)){for(var n;0this.c&&0=i)o=void 0;else{if(1==i)wa(r);else{r[0]=r.pop(),r=0,n=n.a,i=n.length;for(var a=n[r];r>1;){var s=2*r+1,u=2*r+2;if(s=ua.a)break;n[r]=n[s],r=s}n[r]=a}o=o.b}o.apply(this,[e])}},g.ma=function(t){Y.L.ma.call(this,t),this.ua()},g.aa=function(){Y.L.aa.call(this),this.ua()},g.w=function(){Y.L.w.call(this),k.clearTimeout(void 0),wa(this.f.a),this.f=null},u(Z,Y),Z.prototype.qa=function(){var t=new U,e=this.l;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.j&&(t.m=!0),t},Z.prototype.va=function(t){return!t.i&&!t.a},Be.prototype.createWebChannel=Be.prototype.a,X.prototype.send=X.prototype.l,X.prototype.open=X.prototype.j,X.prototype.close=X.prototype.close,yc.NO_ERROR=0,yc.TIMEOUT=8,yc.HTTP_ERROR=6,zc.COMPLETE="complete",Dd.EventType=Ed,Ed.OPEN="a",Ed.CLOSE="b",Ed.ERROR="c",Ed.MESSAGE="d",B.prototype.listen=B.prototype.$,Z.prototype.getObject=Z.prototype.ca,Z.prototype.releaseObject=Z.prototype.hb,U.prototype.listenOnce=U.prototype.Ia,U.prototype.getLastError=U.prototype.$a,U.prototype.getLastErrorCode=U.prototype.Ga,U.prototype.getStatus=U.prototype.V,U.prototype.getStatusText=U.prototype.Ha,U.prototype.getResponseJson=U.prototype.Za,U.prototype.getResponseText=U.prototype.U,U.prototype.getResponseText=U.prototype.U,U.prototype.send=U.prototype.ta,module.exports={createWebChannelTransport:Fe,ErrorCode:yc,EventType:zc,WebChannel:Dd,XhrIoPool:Z}}).call("undefined"!=typeof window?window:this)}},[113])}catch(t){throw Error("Cannot instantiate firebase-firestore.js - be sure to load firebase-app.js first.")} +try{webpackJsonpFirebase([1],{115:function(t,e,n){n(116)},116:function(t,e,n){"use strict";function r(){return te.logLevel===$t.LogLevel.DEBUG?Yt.DEBUG:te.logLevel===$t.LogLevel.SILENT?Yt.SILENT:Yt.ERROR}function i(t){switch(t){case Yt.DEBUG:te.logLevel=$t.LogLevel.DEBUG;break;case Yt.ERROR:te.logLevel=$t.LogLevel.ERROR;break;case Yt.SILENT:te.logLevel=$t.LogLevel.SILENT;break;default:te.error("Firestore ("+Zt+"): Invalid value passed to `setLogLevel`")}}function o(t,e){for(var n=[],r=2;rr)throw new ie(re.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+P(e.length,"argument")+".")}function E(t,e,n,r){if(!(e instanceof Array)||e.length20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=_(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":u("Unknown wrong type: "+typeof t)}function _(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/,n=e.exec(""+t.constructor);if(n&&n.length>1)return n[1]}return null}function O(t,e,n){if(void 0===n)throw new ie(re.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+x(e)+" argument, but it was undefined.")}function M(t,e,n){m(e,function(e,r){if(n.indexOf(e)<0)throw new ie(re.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function L(t,e,n,r){var i=R(r);return new ie(re.INVALID_ARGUMENT,"Function "+t+"() requires its "+x(n)+" argument to be a "+e+", but it was: "+i)}function x(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function P(t,e){return t+" "+e+(1===t?"":"s")}function B(t,e){return te?1:0}function U(t,e){return null!==t&&void 0!==t?!(!e||!t.isEqual(e)):t===e}function q(t,e){if(t.length!==e.length)return!1;for(var n=0;ne?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function j(t,e){return t===e?0!==t||1/t==1/e:t!==t&&e!==e}function W(t){return null===t||void 0===t}function H(t){return Ke(t)&&t<=Qe&&t>=Ge}function z(t,e,n){if(n.isEqual(Ne.INSTANCE)){if(e!==We.EQUAL)throw new ie(re.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new ze(t)}if(n.isEqual(Oe.NAN)){if(e!==We.EQUAL)throw new ie(re.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Xe(t)}return new He(t,e,n)}function X(t){switch(t){case re.OK:return u("Treated status OK as error");case re.CANCELLED:case re.UNKNOWN:case re.DEADLINE_EXCEEDED:case re.RESOURCE_EXHAUSTED:case re.INTERNAL:case re.UNAVAILABLE:case re.UNAUTHENTICATED:return!1;case re.INVALID_ARGUMENT:case re.NOT_FOUND:case re.ALREADY_EXISTS:case re.PERMISSION_DENIED:case re.FAILED_PRECONDITION:case re.ABORTED:case re.OUT_OF_RANGE:case re.UNIMPLEMENTED:case re.DATA_LOSS:return!0;default:return u("Unknown status code: "+t)}}function Y(t){var e=ln[t];if(void 0!==e)return J(e)}function J(t){if(void 0===t)return a("GRPC error has no .code"),re.UNKNOWN;switch(t){case ln.OK:return re.OK;case ln.CANCELLED:return re.CANCELLED;case ln.UNKNOWN:return re.UNKNOWN;case ln.DEADLINE_EXCEEDED:return re.DEADLINE_EXCEEDED;case ln.RESOURCE_EXHAUSTED:return re.RESOURCE_EXHAUSTED;case ln.INTERNAL:return re.INTERNAL;case ln.UNAVAILABLE:return re.UNAVAILABLE;case ln.UNAUTHENTICATED:return re.UNAUTHENTICATED;case ln.INVALID_ARGUMENT:return re.INVALID_ARGUMENT;case ln.NOT_FOUND:return re.NOT_FOUND;case ln.ALREADY_EXISTS:return re.ALREADY_EXISTS;case ln.PERMISSION_DENIED:return re.PERMISSION_DENIED;case ln.FAILED_PRECONDITION:return re.FAILED_PRECONDITION;case ln.ABORTED:return re.ABORTED;case ln.OUT_OF_RANGE:return re.OUT_OF_RANGE;case ln.UNIMPLEMENTED:return re.UNIMPLEMENTED;case ln.DATA_LOSS:return re.DATA_LOSS;default:return u("Unknown status code: "+t)}}function Z(t){if(void 0===t)return ln.OK;switch(t){case re.OK:return ln.OK;case re.CANCELLED:return ln.CANCELLED;case re.UNKNOWN:return ln.UNKNOWN;case re.DEADLINE_EXCEEDED:return ln.DEADLINE_EXCEEDED;case re.RESOURCE_EXHAUSTED:return ln.RESOURCE_EXHAUSTED;case re.INTERNAL:return ln.INTERNAL;case re.UNAVAILABLE:return ln.UNAVAILABLE;case re.UNAUTHENTICATED:return ln.UNAUTHENTICATED;case re.INVALID_ARGUMENT:return ln.INVALID_ARGUMENT;case re.NOT_FOUND:return ln.NOT_FOUND;case re.ALREADY_EXISTS:return ln.ALREADY_EXISTS;case re.PERMISSION_DENIED:return ln.PERMISSION_DENIED;case re.FAILED_PRECONDITION:return ln.FAILED_PRECONDITION;case re.ABORTED:return ln.ABORTED;case re.OUT_OF_RANGE:return ln.OUT_OF_RANGE;case re.UNIMPLEMENTED:return ln.UNIMPLEMENTED;case re.DATA_LOSS:return ln.DATA_LOSS;default:return u("Unknown status code: "+t)}}function $(t){switch(t){case 200:return re.OK;case 400:return re.INVALID_ARGUMENT;case 401:return re.UNAUTHENTICATED;case 403:return re.PERMISSION_DENIED;case 404:return re.NOT_FOUND;case 409:return re.ABORTED;case 416:return re.OUT_OF_RANGE;case 429:return re.RESOURCE_EXHAUSTED;case 499:return re.CANCELLED;case 500:return re.UNKNOWN;case 501:return re.UNIMPLEMENTED;case 503:return re.UNAVAILABLE;case 504:return re.DEADLINE_EXCEEDED;default:return t>=200&&t<300?re.OK:t>=400&&t<500?re.FAILED_PRECONDITION:t>=500&&t<600?re.INTERNAL:re.UNKNOWN}}function tt(){return En}function et(){return Tn}function nt(){return In}function rt(){return Sn}function it(t,e){e.length>0&&(t.resumeToken=e)}function ot(t,e){c(!W(t),e+" is missing")}function at(t){return"number"==typeof t?t:"string"==typeof t?+t:u("can't parse "+t)}function st(t,e,n){return e===n||!e&&n in t}function ut(t){if(t.search(Wn)>=0)throw new ie(re.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(jn.bind.apply(jn,[void 0].concat(t.split("."))))}catch(e){throw new ie(re.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}function ct(t,e){var n=function(t){switch(t){case Hn.Added:return 1;case Hn.Modified:case Hn.Metadata:return 2;case Hn.Removed:return 0;default:return u("Unknown ChangeType: "+t)}};return n(t)-n(e)}function ht(t){for(var e="",n=0;n0&&(e=ft(e)),e=lt(t.get(n),e);return ft(e)}function lt(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+t),2===e)return c(t.charAt(0)===br&&t.charAt(1)===wr,"Non-empty path "+t+" had length 2"),de.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;on)&&u('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case wr:var s=t.substring(o,a),h=void 0;0===i.length?h=s:(i+=s,h=i,i=""),r.push(h);break;case Er:i+=t.substring(o,a),i+="\0";break;case Tr:i+=t.substring(o,a+1);break;default:u('Invalid encoded resource path: "'+t+'"')}o=a+2}return new de(r)}function pt(t,e,n,r){c(n=0&&r<=2,"Unexpected schema upgrade from v${fromVersion} to v{toVersion}."),n<1&&r>=1&&(mt(t),yt(t),vt(t),gt(t));var i=rr.resolve();return n<2&&r>=2&&(i=wt(e).next(function(t){return bt(e,t)})),i}function mt(t){t.createObjectStore(Sr.store)}function yt(t){t.createObjectStore(Dr.store,{keyPath:Dr.keyPath}),t.createObjectStore(Cr.store,{keyPath:Cr.keyPath}),t.createObjectStore(kr.store)}function gt(t){t.createObjectStore(Ar.store)}function vt(t){t.createObjectStore(_r.store,{keyPath:_r.keyPath}).createIndex(_r.documentTargetsIndex,_r.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Rr.store,{keyPath:Rr.keyPath}).createIndex(Rr.queryTargetsIndexName,Rr.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Or.store)}function bt(t,e){var n=t.store(Or.store);return t.store(Rr.store).count().next(function(t){return e.targetCount=t,n.put(Or.key,e)})}function wt(t){var e=t.store(Or.store);return e.get(Or.key).next(function(t){return null!=t?rr.resolve(t):(t=new Or(0,0,rn.MIN.toTimestamp(),0),e.put(Or.key,t).next(function(){return t}))})}function Et(t){return new rr(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}function Tt(t){return c("string"==typeof t,"Persisting non-string stream token not supported."),t}function It(t){return Ct(t,Cr.store)}function St(t){return Ct(t,kr.store)}function Dt(t){return Ct(t,Dr.store)}function Ct(t,e){return t instanceof Pr?t.store(e):u("Invalid transaction object provided!")}function kt(t){return Rt(t,Rr.store)}function Nt(t){return Rt(t,Or.store)}function At(t){return Rt(t,_r.store)}function Rt(t,e){return t instanceof Pr?t.store(e):u("Invalid transaction object provided!")}function _t(t){return t instanceof Pr?t.store(Ar.store):u("Invalid transaction object provided!")}function Ot(t){return t.path.toArray()}function Mt(t){return void 0!==t.documents}function Lt(t){if(!t)return new bi;switch(t.type){case"gapi":return new Ti(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new ie(re.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function xt(t){return Pt(t,["next","error","complete"])}function Pt(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,i=e;r=0,"Index for document not found"),i=i.delete(n.doc.key)),n.type!==Hn.Removed&&(i=i.add(n.doc),a=i.indexOf(n.doc.key)),{type:Ht(n.type),doc:r,oldIndex:o,newIndex:a}})}function Ht(t){switch(t){case Hn.Added:return"added";case Hn.Modified:case Hn.Metadata:return"modified";case Hn.Removed:return"removed";default:return u("Unknown change type: "+t)}}function zt(t){t.INTERNAL.registerService("firestore",function(t){return new Bi(t)},g(no))}function Xt(t){zt(t)}Object.defineProperty(e,"__esModule",{value:!0});var Yt,Jt=n(7),Zt=Jt.default.SDK_VERSION,$t=n(22),te=new $t.Logger("@firebase/firestore");!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(Yt||(Yt={}));var ee=function(){function t(){}return t.setPlatform=function(e){t.platform&&u("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||u("Platform not set"),t.platform},t}(),ne=n(2),re={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},ie=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return ne.__extends(e,t),e}(Error),oe=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return c(20===e.length,"Invalid auto ID: "+e),e},t}(),ae=function(){function t(t){Q(),this.e=t}return t.fromBase64String=function(e){v("Blob.fromBase64String",arguments,1),T("Blob.fromBase64String","string",1,e),Q();try{return new t(ee.getPlatform().atob(e))}catch(t){throw new ie(re.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(v("Blob.fromUint8Array",arguments,1),G(),!(e instanceof Uint8Array))throw L("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return v("Blob.toBase64",arguments,0),Q(),ee.getPlatform().btoa(this.e)},t.prototype.toUint8Array=function(){v("Blob.toUint8Array",arguments,0),G();for(var t=new Uint8Array(this.e.length),e=0;e90)throw new ie(re.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new ie(re.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this.r=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this.r},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this._lat===t._lat&&this.r===t.r},t.prototype.n=function(t){return B(this._lat,t._lat)||B(this.r,t.r)},t}(),ce=function(){function t(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}return t}(),he="(default)",le=function(){function t(t,e){this.projectId=t,this.database=e||he}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===he},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return B(this.projectId,t.projectId)||B(this.database,t.database)},t}(),fe=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&u("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&u("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):u("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,c(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return c(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return c(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return c(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return c(to)return 1}return t.lengthe.length?1:0},t}(),de=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne.__extends(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new ie(re.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(fe),pe=/^[_a-zA-Z][_a-zA-Z0-9]*$/,me=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne.__extends(e,t),e.isValidIdentifier=function(t){return pe.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new ie(re.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;i0&&(e=e.right)}return null},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(){return new we(this.root,null,this.comparator,!1)},t.prototype.getIteratorFrom=function(t){return new we(this.root,t,this.comparator,!1)},t.prototype.getReverseIterator=function(){return new we(this.root,null,this.comparator,!0)},t.prototype.getReverseIteratorFrom=function(t){return new we(this.root,t,this.comparator,!0)},t}(),we=function(){function t(t,e,n,r){this.isReverse=r,this.nodeStack=[];for(var i=1;!t.isEmpty();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(0===i){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){c(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.nodeStack.pop(),e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}},t}(),Ee=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,i=n(t,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n)),r.fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(e,i.key)){if(i.right.isEmpty())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(e,n))}return i.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw u("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw u("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw u("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),Te=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new Ee(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();Ee.EMPTY=new Te;var Ie;!function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(Ie||(Ie={}));var Se;!function(t){t[t.Default=0]="Default",t[t.Estimate=1]="Estimate",t[t.Previous=2]="Previous"}(Se||(Se={}));var De,Ce=function(){function t(t){this.serverTimestampBehavior=t}return t.fromSnapshotOptions=function(e){switch(e.serverTimestamps){case"estimate":return new t(Se.Estimate);case"previous":return new t(Se.Previous);case"none":case void 0:return t.defaultOptions;default:return u("fromSnapshotOptions() called with invalid options.")}},t.defaultOptions=new t(Se.Default),t}(),ke=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":""+t},t.prototype.defaultCompareTo=function(t){return c(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),B(this.typeOrder,t.typeOrder)},t}(),Ne=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=Ie.NullValue,e.internalValue=null,e}return ne.__extends(e,t),e.prototype.value=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(ke),Ae=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.BooleanValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?B(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(ke),Re=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.NumberValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?K(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ke),_e=function(t){function e(e){return t.call(this,e)||this}return ne.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&j(this.internalValue,t.internalValue)},e}(Re),Oe=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return ne.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&j(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(Re),Me=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.StringValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?B(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ke),Le=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.TimestampValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.compareTo(t.internalValue):t instanceof xe?-1:this.defaultCompareTo(t)},e}(ke),xe=function(t){function e(e,n){var r=t.call(this)||this;return r.localWriteTime=e,r.previousValue=n,r.typeOrder=Ie.TimestampValue,r}return ne.__extends(e,t),e.prototype.value=function(t){return t&&t.serverTimestampBehavior===Se.Estimate?this.localWriteTime.toDate():t&&t.serverTimestampBehavior===Se.Previous&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.localWriteTime.isEqual(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime.compareTo(t.localWriteTime):t instanceof Le?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(ke),Pe=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.BlobValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.n(t.internalValue):this.defaultCompareTo(t)},e}(ke),Be=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=Ie.RefValue,r}return ne.__extends(e,t),e.prototype.value=function(t){return this.key},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId)},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:ye.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(ke),Ue=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.GeoPointValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.n(t.internalValue):this.defaultCompareTo(t)},e}(ke),qe=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.ObjectValue,n}return ne.__extends(e,t),e.prototype.value=function(t){var e={};return this.internalValue.inorderTraversal(function(n,r){e[n]=r.value(t)}),e},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.isEqual(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),a=B(i.key,o.key)||i.value.compareTo(o.value);if(a)return a}return B(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(c(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var i=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),i)},e.prototype.delete=function(t){if(c(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){c(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e?n.internalValue.get(t)||void 0:void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new be(B)),e}(ke),Fe=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Ie.ArrayValue,n}return ne.__extends(e,t),e.prototype.value=function(t){return this.internalValue.map(function(e){return e.value(t)})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.isEqual=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Ye.ASCENDING;this.memoizedOrderBy.push(a===Ye.ASCENDING?$e:tn)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){c(null==this.getInequalityFilterField()||!(e instanceof He)||!e.isInequality()||e.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),c(!ye.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){c(!ye.isDocumentKey(this.path),"No ordering allowed for document query"),c(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),W(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;default:return u("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.isEqual=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t}(),He=function(){function t(t,e,n){this.field=t,this.op=e,this.value=n}return t.prototype.matches=function(t){if(this.field.isKeyField()){c(this.value instanceof Be,"Comparing on key, but filter value not a RefValue");var e=this.value,n=ye.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(t){return this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(t){switch(this.op){case We.LESS_THAN:return t<0;case We.LESS_THAN_OR_EQUAL:return t<=0;case We.EQUAL:return 0===t;case We.GREATER_THAN:return t>0;case We.GREATER_THAN_OR_EQUAL:return t>=0;default:return u("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==We.EQUAL},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.op+this.value},t.prototype.isEqual=function(e){return e instanceof t&&this.op.isEqual(e.op)&&this.field.isEqual(e.field)&&this.value.isEqual(e.value)},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(),ze=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.isEqual=function(e){return e instanceof t&&this.field.isEqual(e.field)},t}(),Xe=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field).value();return"number"==typeof e&&isNaN(e)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.isEqual=function(e){return e instanceof t&&this.field.isEqual(e.field)},t}(),Ye=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),Je=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0,"timestamp nanoseconds out of range: "+e),c(e<1e9,"timestamp nanoseconds out of range"+e),c(t>=-62135596800,"timestamp seconds out of range: "+t),c(t<253402300800,"timestamp seconds out of range"+t)}return t.now=function(){return t.fromEpochMilliseconds(Date.now())},t.fromDate=function(e){return t.fromEpochMilliseconds(e.getTime())},t.fromEpochMilliseconds=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.fromISOString=function(e){var n=0,r=en.exec(e);if(c(!!r,"invalid timestamp: "+e),r[1]){var i=r[1];i=(i+"000000000").substr(0,9),n=+i}var o=new Date(e);return new t(Math.floor(o.getTime()/1e3),n)},t.prototype.toDate=function(){return new Date(this.toEpochMilliseconds())},t.prototype.toEpochMilliseconds=function(){return 1e3*this.seconds+this.nanos/1e6},t.prototype.compareTo=function(t){return this.seconds===t.seconds?B(this.nanos,t.nanos):B(this.seconds,t.seconds)},t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanos===this.nanos},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanos="+this.nanos+")"},t}(),rn=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new nn(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp.compareTo(t.timestamp)},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanos/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new nn(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(De||(De={}));var on,an=function(){function t(t,e,n,r,i){void 0===r&&(r=rn.MIN),void 0===i&&(i=h()),this.query=t,this.targetId=e,this.purpose=n,this.snapshotVersion=r,this.resumeToken=i}return t.prototype.update=function(e){return new t(this.query,this.targetId,this.purpose,e.snapshotVersion,e.resumeToken)},t.prototype.isEqual=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.snapshotVersion.isEqual(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.isEqual(t.query)},t}(),sn=function(){function t(t){this.fields=t}return t.prototype.isEqual=function(t){return q(this.fields,t.fields)},t}(),un=function(){function t(){}return t.prototype.isEqual=function(e){return e instanceof t},t.instance=new t,t}(),cn=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.isEqual=function(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)},t}(),hn=function(){function t(t,e){this.version=t,this.transformResults=e}return t}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(on||(on={}));var ln,fn=function(){function t(t,e){this.updateTime=t,this.exists=e,c(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof ge&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists?t instanceof ge:null===t||t instanceof ve:(c(this.isNone,"Precondition should be empty"),!0)},t.prototype.isEqual=function(t){return U(this.updateTime,t.updateTime)&&this.exists===t.exists},t.NONE=new t,t}(),dn=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&c(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof ge?t.version:rn.MIN},t}(),pn=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.value=n,i.precondition=r,i.type=on.Set,i}return ne.__extends(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by SetMutation.");var n=dn.getPostMutationVersion(t);return new ge(this.key,n,this.value,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=dn.getPostMutationVersion(t);return new ge(this.key,r,this.value,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this.precondition.isEqual(t.precondition)},e}(dn),mn=function(t){function e(e,n,r,i){var o=t.call(this)||this;return o.key=e,o.data=n,o.fieldMask=r,o.precondition=i,o.type=on.Patch,o}return ne.__extends(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return t;var n=dn.getPostMutationVersion(t),r=this.patchDocument(t);return new ge(this.key,n,r,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=dn.getPostMutationVersion(t),i=this.patchDocument(t);return new ge(this.key,r,i,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.fieldMask.isEqual(t.fieldMask)&&this.precondition.isEqual(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof ge?t.data:qe.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){for(var e=0,n=this.fieldMask.fields;e=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),En=new be(ye.comparator),Tn=new be(ye.comparator),In=new be(ye.comparator),Sn=new wn(ye.comparator),Dn=function(){function t(t,e,n){this.snapshotVersion=t,this.targetChanges=e,this.documentUpdates=n}return t.prototype.addDocumentUpdate=function(t){this.documentUpdates=this.documentUpdates.insert(t.key,t)},t.prototype.handleExistenceFilterMismatch=function(t){this.targetChanges[t]={mapping:new Nn,snapshotVersion:rn.MIN,currentStatusUpdate:bn.MarkNotCurrent,resumeToken:h()}},t}();!function(t){t[t.None=0]="None",t[t.MarkNotCurrent=1]="MarkNotCurrent",t[t.MarkCurrent=2]="MarkCurrent"}(bn||(bn={}));var Cn,kn=rt(),Nn=function(){function t(){this.docs=kn}return Object.defineProperty(t.prototype,"documents",{get:function(){return this.docs},enumerable:!0,configurable:!0}),t.prototype.add=function(t){this.docs=this.docs.add(t)},t.prototype.delete=function(t){this.docs=this.docs.delete(t)},t.prototype.isEqual=function(t){return null!==t&&this.docs.isEqual(t.docs)},t}(),An=function(){function t(){this.addedDocuments=kn,this.removedDocuments=kn}return t.prototype.applyToKeySet=function(t){var e=t;return this.addedDocuments.forEach(function(t){return e=e.add(t)}),this.removedDocuments.forEach(function(t){return e=e.delete(t)}),e},t.prototype.add=function(t){this.addedDocuments=this.addedDocuments.add(t),this.removedDocuments=this.removedDocuments.delete(t)},t.prototype.delete=function(t){this.addedDocuments=this.addedDocuments.delete(t),this.removedDocuments=this.removedDocuments.add(t)},t.prototype.isEqual=function(t){return null!==t&&this.addedDocuments.isEqual(t.addedDocuments)&&this.removedDocuments.isEqual(t.removedDocuments)},t}(),Rn=function(){function t(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}return t}(),_n=function(){function t(t,e){this.targetId=t,this.existenceFilter=e}return t}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(Cn||(Cn={}));var On=function(){function t(t,e,n,r){void 0===n&&(n=h()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}return t}(),Mn=function(){function t(t,e,n){this.snapshotVersion=t,this.listenTargets=e,this.existenceFilters={},this.targetChanges={},this.documentUpdates=tt(),this.frozen=!1,this.pendingTargetResponses=g(n)}return t.prototype.add=function(t){c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t instanceof Rn?this.addDocumentChange(t):t instanceof On?this.addTargetChange(t):t instanceof _n?this.addExistenceFilterChange(t):u("Unknown watch change: "+t)},t.prototype.addChanges=function(t){var e=this;c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t.forEach(function(t){return e.add(t)})},t.prototype.createRemoteEvent=function(){var t=this,e=this.targetChanges;return p(this.targetChanges,function(n){t.isActiveTarget(n)||delete e[n]}),this.frozen=!0,new Dn(this.snapshotVersion,e,this.documentUpdates)},t.prototype.ensureTargetChange=function(t){var e=this.targetChanges[t];return e||(e={currentStatusUpdate:bn.None,snapshotVersion:this.snapshotVersion,mapping:new An,resumeToken:h()},this.targetChanges[t]=e),e},t.prototype.isActiveTarget=function(t){return!f(this.pendingTargetResponses,t)&&f(this.listenTargets,t)},t.prototype.addDocumentChange=function(t){for(var e=!1,n=0,r=t.updatedTargetIds;n4&&"documents"===t.get(4),"tried to deserialize invalid key "+t),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof Ne)return{nullValue:"NULL_VALUE"};if(t instanceof Ae)return{booleanValue:t.value()};if(t instanceof _e)return{integerValue:""+t.value()};if(t instanceof Oe){var e=t.value();if(this.options.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof Me?{stringValue:t.value()}:t instanceof qe?{mapValue:this.toMapValue(t)}:t instanceof Fe?{arrayValue:this.toArrayValue(t)}:t instanceof Le?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ue?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof Pe?{bytesValue:this.toBytes(t.value())}:t instanceof Be?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:u("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(st(t,n,"nullValue"))return Ne.INSTANCE;if(st(t,n,"booleanValue"))return Ae.of(t.booleanValue);if(st(t,n,"integerValue"))return new _e(at(t.integerValue));if(st(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return Oe.NAN;if("Infinity"===t.doubleValue)return Oe.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return Oe.NEGATIVE_INFINITY}return new Oe(t.doubleValue)}if(st(t,n,"stringValue"))return new Me(t.stringValue);if(st(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(st(t,n,"arrayValue")){ot(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new Fe(r.map(function(t){return e.fromValue(t)}))}if(st(t,n,"timestampValue"))return ot(t.timestampValue,"timestampValue"),new Le(this.fromTimestamp(t.timestampValue));if(st(t,n,"geoPointValue")){ot(t.geoPointValue,"geoPointValue");var i=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new Ue(new ue(i,o))}if(st(t,n,"bytesValue")){ot(t.bytesValue,"bytesValue");var a=this.fromBlob(t.bytesValue);return new Pe(a)}if(st(t,n,"referenceValue")){ot(t.referenceValue,"referenceValue");var s=this.fromResourceName(t.referenceValue),c=new le(s.get(1),s.get(3)),h=new ye(this.extractLocalPathFromResourceName(s));return new Be(c,h)}return u("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return c(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t){return new ge(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasLocalMutations:!1})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=qe.EMPTY;return m(n,function(t,n){r=r.set(new me([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){c(!!t.found,"Tried to deserialize a found document from a missing document."),ot(t.found.name,"doc.found.name"),ot(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new ge(e,n,r,{hasLocalMutations:!1})},t.prototype.fromMissing=function(t){c(!!t.missing,"Tried to deserialize a missing document from a found document."),c(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new ve(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result;return st(t,e,"found")?this.fromFound(t):st(t,e,"missing")?this.fromMissing(t):u("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case Cn.Added:return"ADD";case Cn.Current:return"CURRENT";case Cn.NoChange:return"NO_CHANGE";case Cn.Removed:return"REMOVE";case Cn.Reset:return"RESET";default:return u("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof _n)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof Rn){if(t.newDoc instanceof ge){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof ve){var e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof On){var n=void 0;return t.cause&&(n={code:Z(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return u("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.response_type;if(st(t,n,"targetChange")){ot(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),a=t.targetChange.cause,s=a&&this.fromRpcStatus(a);e=new On(r,i,o,s||null)}else if(st(t,n,"documentChange")){ot(t.documentChange,"documentChange"),ot(t.documentChange.document,"documentChange.name"),ot(t.documentChange.document.name,"documentChange.document.name"),ot(t.documentChange.document.updateTime,"documentChange.document.updateTime");var c=t.documentChange,h=this.fromName(c.document.name),l=this.fromVersion(c.document.updateTime),f=this.fromFields(c.document.fields||{}),d=new ge(h,l,f,{hasLocalMutations:!1}),p=c.targetIds||[],m=c.removedTargetIds||[];e=new Rn(p,m,d.key,d)}else if(st(t,n,"documentDelete")){ot(t.documentDelete,"documentDelete"),ot(t.documentDelete.document,"documentDelete.document");var y=t.documentDelete,h=this.fromName(y.document),l=y.readTime?this.fromVersion(y.readTime):rn.forDeletedDoc(),d=new ve(h,l),m=y.removedTargetIds||[];e=new Rn([],m,d.key,d)}else if(st(t,n,"documentRemove")){ot(t.documentRemove,"documentRemove"),ot(t.documentRemove.document,"documentRemove");var g=t.documentRemove,h=this.fromName(g.document),m=g.removedTargetIds||[];e=new Rn([],m,h,null)}else{if(!st(t,n,"filter"))return u("Unknown change type "+JSON.stringify(t));ot(t.filter,"filter"),ot(t.filter.targetId,"filter.targetId");var v=t.filter,b=v.count||0,w=new vn(b),E=v.targetId;e=new _n(E,w)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?Cn.NoChange:"ADD"===t?Cn.Added:"REMOVE"===t?Cn.Removed:"CURRENT"===t?Cn.Current:"RESET"===t?Cn.Reset:u("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!st(t,t.response_type,"targetChange"))return rn.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?rn.MIN:e.readTime?this.fromVersion(e.readTime):rn.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof pn)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof gn)e={delete:this.toName(t.key)};else if(t instanceof mn)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof yn))return u("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):fn.NONE;if(t.update){ot(t.update.name,"name");var r=this.fromName(t.update.name),i=this.fromFields(t.update.fields||{});if(t.updateMask){var o=this.fromDocumentMask(t.updateMask);return new mn(r,i,o,n)}return new pn(r,i,n)}if(t.delete){var r=this.fromName(t.delete);return new gn(r,n)}if(t.transform){var r=this.fromName(t.transform.document),a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return c(!0===n.exists,'Transforms only support precondition "exists == true"'),new yn(r,a)}return u("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return c(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:u("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?fn.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?fn.exists(t.exists):fn.NONE},t.prototype.fromWriteResult=function(t){var e=this,n=t.updateTime?this.fromVersion(t.updateTime):null,r=null;return t.transformResults&&t.transformResults.length>0&&(r=t.transformResults.map(function(t){return e.fromValue(t)})),new hn(n,r)},t.prototype.fromWriteResults=function(t){var e=this;return(t||[]).map(function(t){return e.fromWriteResult(t)})},t.prototype.toFieldTransform=function(t){return c(t.transform instanceof un,"Unknown transform: "+t.transform),{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"}},t.prototype.fromFieldTransform=function(t){c("REQUEST_TIME"===t.setToServerValue,"Unknown transform proto: "+JSON.stringify(t));var e=me.fromServerFormat(t.fieldPath);return new cn(e,un.instance)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;c(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return je.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(de.EMPTY_PATH);else{var n=t.path;c(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var i=this.toOrder(t.orderBy);i&&(e.structuredQuery.orderBy=i);var o=this.toInt32Value(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){c(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];e=e.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new je(e,a,o,s,u,h)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case De.Listen:return null;case De.ExistenceFilterMismatch:return"existence-filter-mismatch";case De.LimboResolution:return"limbo-document";default:return u("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)},e.targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof He?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):u("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new Je(r,n)},t.prototype.toDirection=function(t){return Ln[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Ye.ASCENDING;case"DESCENDING":return Ye.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return xn[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return We.EQUAL;case"GREATER_THAN":return We.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return We.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return We.LESS_THAN;case"LESS_THAN_OR_EQUAL":return We.LESS_THAN_OR_EQUAL;case"OPERATOR_UNSPECIFIED":return u("Unspecified relation");default:return u("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return me.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new Ze(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof He?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new He(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Xe?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof ze?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Xe(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new ze(n);case"OPERATOR_UNSPECIFIED":return u("Unspecified filter");default:return u("Unknown filter")}},t.prototype.toDocumentMask=function(t){return{fieldPaths:t.fields.map(function(t){return t.canonicalString()})}},t.prototype.fromDocumentMask=function(t){var e=t.fieldPaths||[],n=e.map(function(t){return me.fromServerFormat(t)});return new sn(n)},t}(),Bn=n(117),Un=function(){function t(t){this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){c(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){c(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){c(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){c(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){c(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){c(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}(),qn="Connection",Fn={BatchGetDocuments:"batchGet",Commit:"commit"},Vn="gl-js/ fire/"+Zt,Gn=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Bn.XhrIoPool;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Vn},t.prototype.invokeRPC=function(t,e,n){var r=this,i=this.makeUrl(t);return new Promise(function(a,s){r.pool.getObject(function(c){c.listenOnce(Bn.EventType.COMPLETE,function(){try{switch(c.getLastErrorCode()){case Bn.ErrorCode.NO_ERROR:var e=c.getResponseJson();o(qn,"XHR received:",JSON.stringify(e)),a(e);break;case Bn.ErrorCode.TIMEOUT:o(qn,'RPC "'+t+'" timed out'),s(new ie(re.DEADLINE_EXCEEDED,"Request time out"));break;case Bn.ErrorCode.HTTP_ERROR:var n=c.getStatus();o(qn,'RPC "'+t+'" failed with status:',n,"response text:",c.getResponseText()),n>0?s(new ie($(n),"Server responded with status "+c.getStatusText())):(o(qn,'RPC "'+t+'" failed'),s(new ie(re.UNAVAILABLE,"Connection failed.")));break;default:u('RPC "'+t+'" failed with unanticipated webchannel error '+c.getLastErrorCode()+": "+c.getLastError()+", giving up.")}}finally{o(qn,'RPC "'+t+'" completed.'),r.pool.releaseObject(c)}});var h=JSON.stringify(e);o(qn,"XHR sending: ",i+" "+h);var l={"Content-Type":"text/plain"};r.modifyHeadersForRequest(l,n),c.send(i,"POST",h,l,15)})})},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1beta1.Firestore","/",t,"/channel"],r=Object(Bn.createWebChannelTransport)(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},httpHeadersOverwriteParam:"$httpHeaders",messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(i.initMessageHeaders,e);var a=n.join("");o(qn,"Creating WebChannel: "+a+" "+i);var s=r.createWebChannel(a,i),u=!1,h=!1,l=new Un({sendFn:function(t){h?o(qn,"Not sending because WebChannel is closed:",t):(u||(o(qn,"Opening WebChannel transport."),s.open(),u=!0),o(qn,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}}),f=function(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return f(Bn.WebChannel.EventType.OPEN,function(){h||o(qn,"WebChannel transport opened.")}),f(Bn.WebChannel.EventType.CLOSE,function(){h||(h=!0,o(qn,"WebChannel transport closed"),l.callOnClose())}),f(Bn.WebChannel.EventType.ERROR,function(t){h||(h=!0,o(qn,"WebChannel transport errored:",t),l.callOnClose(new ie(re.UNAVAILABLE,"The operation could not be completed")))}),f(Bn.WebChannel.EventType.MESSAGE,function(t){if(!h){var e=t.data[0];c(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){o(qn,"WebChannel received error:",n);var r=n.status,i=Y(r),a=n.message;void 0===i&&(i=re.INTERNAL,a="Unknown error status: "+r+" with message "+n.message),h=!0,l.callOnClose(new ie(i,a)),s.close()}else o(qn,"WebChannel received:",e),l.callOnMessage(e)}}),setTimeout(function(){l.callOnOpen()},0),l},t.prototype.makeUrl=function(t){var e=Fn[t];c(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1beta1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),Qn=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return t.prototype.loadConnection=function(t){return Promise.resolve(new Gn(t))},t.prototype.newSerializer=function(t){return new Pn(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();ee.setPlatform(new Qn);var Kn,jn=function(){function t(){for(var t=[],e=0;e=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]})})},t.prototype.onChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeDocumentMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeQueryMetadataChanges},t.prototype.raiseInitialEvent=function(e){c(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e=new Jn(e.query,e.docs,Zn.emptySet(e.docs),t.getInitialViewChanges(e),e.fromCache,e.hasPendingWrites,!0),this.raisedInitialEvent=!0,this.queryObserver.next(e)},t.getInitialViewChanges=function(t){var e=[];return t.docs.forEach(function(t){e.push({type:Hn.Added,doc:t})}),e},t}(),rr=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&u("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,i){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,i)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,i)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return e.reduce(function(t,e,n){return t.next(function(){return e})},t.resolve())},t.map=function(e){var n=[],r=!0,i=t.resolve(null);return e.reduce(function(t,e){return t.next(function(t){return r||n.push(t),r=!1,e})},i).next(function(t){return n.push(t),n})},t}(),ir=function(){function t(){this.isEager=!0,this.sources=[],this.potentialGarbage=rt()}return t.prototype.addGarbageSource=function(t){this.sources.push(t),t.setGarbageCollector(this)},t.prototype.removeGarbageSource=function(t){this.sources.splice(this.sources.indexOf(t),1),t.setGarbageCollector(null)},t.prototype.addPotentialGarbageKey=function(t){this.potentialGarbage=this.potentialGarbage.add(t)},t.prototype.collectGarbage=function(t){var e=this,n=[],r=rt();return this.potentialGarbage.forEach(function(i){var o=e.documentHasAnyReferences(t,i);n.push(o.next(function(t){return t||(r=r.add(i)),rr.resolve()}))}),this.potentialGarbage=rt(),rr.waitFor(n).next(function(){return r})},t.prototype.documentHasAnyReferences=function(t,e){var n=rr.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(t,e)}}).reduce(function(t,e){return t.next(function(t){return t?rr.resolve(!0):e()})},n)},t}(),or=function(){function t(t,e,n){this.query=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e){for(var n=rt(),r=rt(),i=0,o=e.docChanges;i>ur<=t?n|this.generatorId:(n|this.generatorId)-(1<=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!W(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),p(t.targetChanges,function(n,r){var i=e.limboKeysByTarget[n];i&&r.currentStatusUpdate===bn.MarkCurrent&&!t.documentUpdates.get(i)&&t.addDocumentUpdate(new ve(i,t.snapshotVersion))}),this.localStore.applyRemoteEvent(t).then(function(n){return e.emitNewSnapsAndNotifyLocalStore(n,t)})},t.prototype.applyOnlineStateChange=function(t){var e=[];this.queryViewsByQuery.forEach(function(n,r){var i=r.view.applyOnlineStateChange(t);c(0===i.limboChanges.length,"OnlineState should not affect limbo documents."),i.snapshot&&e.push(i.snapshot)}),this.viewHandler(e)},t.prototype.rejectListen=function(t,e){var n=this;this.assertSubscribed("rejectListens()");var r=this.limboKeysByTarget[t];if(r){this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboKeysByTarget[t];var i=new be(ye.comparator);i=i.insert(r,new ve(r,rn.forDeletedDoc()));var o=new Dn(rn.MIN,{},i);return this.applyRemoteEvent(o)}var a=this.queryViewsByTarget[t];return c(!!a,"Unknown targetId: "+t),this.localStore.releaseQuery(a.query).then(function(){return n.removeAndCleanupQuery(a).then(function(){n.errorHandler(a.query,e)})})},t.prototype.applySuccessfulWrite=function(t){var e=this;return this.assertSubscribed("applySuccessfulWrite()"),this.processUserCallback(t.batch.batchId,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(t){return n.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new be(B)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(c(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){return this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.limboDocumentRefs.removeReferencesForId(t.targetId),this.gcLimboDocuments()},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.prototype.runTransaction=function(t,e,n){var r=Pr.open(this.db,t,e),i=n(r).catch(function(t){return r.abort(),rr.reject(t)}).toPromise();return r.completionPromise.then(function(){return i})},t.prototype.close=function(){this.db.close()},t}(),xr=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return Et(this.dbCursor.delete())},t}(),Pr=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.completionPromise=new Promise(function(t,n){e.transaction.onabort=e.transaction.oncomplete=function(e){t()},e.transaction.onerror=function(t){n(t.target.error)}})}return t.open=function(e,n,r){return new t(e.transaction(r,n))},t.prototype.abort=function(){this.aborted||(o("SimpleDb","Aborting transaction."),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return c(!!e,"Object store not part of transaction: "+t),new Br(e)},t}(),Br=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(o("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(o("SimpleDb","PUT",this.store.name,"",t),n=this.store.put(t)),Et(n)},t.prototype.get=function(t){var e=this;return Et(this.store.get(t)).next(function(n){return void 0===n&&(n=null),o("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return o("SimpleDb","DELETE",this.store.name,t),Et(this.store.delete(t))},t.prototype.count=function(){return o("SimpleDb","COUNT",this.store.name),Et(this.store.count())},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){o("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateCursor=function(t,e){var n=[];return new rr(function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(!i)return void r();var o=new xr(i),a=e(i.primaryKey,i.value,o);a instanceof rr&&n.push(a),o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}}).next(function(){return rr.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(c(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}(),Ur=function(){function t(t,e){this.userId=t,this.serializer=e,this.garbageCollector=null}return t.forUser=function(e,n){return c(""!==e.uid,"UserID must not be an empty string."),new t(e.isAuthenticated()?e.uid:"",n)},t.prototype.start=function(e){var n=this;return t.loadNextBatchIdFromDb(e).next(function(t){return n.nextBatchId=t,Dt(e).get(n.userId)}).next(function(t){return t||(t=new Dr(n.userId,yr,"")),n.metadata=t,n.metadata.lastAcknowledgedBatchId>=n.nextBatchId?n.checkEmpty(e).next(function(t){return c(t,"Reset nextBatchID is only possible when the queue is empty"),n.metadata.lastAcknowledgedBatchId=yr,Dt(e).put(n.metadata)}):rr.resolve()})},t.loadNextBatchIdFromDb=function(t){var e=yr;return It(t).iterate({reverse:!0},function(t,n,r){var i=t[0];if(t[1]>e&&(e=n.batchId),""===i)r.done();else{var o=F(i);r.skip([o])}}).next(function(){return e+1})},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY),this.keyForBatchId(Number.POSITIVE_INFINITY));return It(t).iterate({range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.getNextBatchId=function(t){return rr.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return rr.resolve(this.metadata.lastAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;return c(r>this.metadata.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),this.metadata.lastAcknowledgedBatchId=r,this.metadata.lastStreamToken=Tt(n),Dt(t).put(this.metadata)},t.prototype.getLastStreamToken=function(t){return rr.resolve(this.metadata.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.metadata.lastStreamToken=Tt(e),Dt(t).put(this.metadata)},t.prototype.addMutationBatch=function(t,e,n){var r=this,i=this.nextBatchId;this.nextBatchId++;var o=new gr(i,e,n),a=this.serializer.toDbMutationBatch(this.userId,o);return It(t).put(a).next(function(){for(var e=[],o=0,a=n;o=r,"Should have found mutation after "+r),o=n.serializer.fromDbMutationBatch(e)),i.done()}).next(function(){return o})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound(this.keyForBatchId(yr),this.keyForBatchId(Number.POSITIVE_INFINITY));return It(t).loadAll(n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this,r=IDBKeyRange.bound(this.keyForBatchId(yr),this.keyForBatchId(e));return It(t).loadAll(r).next(function(t){return t.map(function(t){return n.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=kr.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];return St(t).iterate({range:i},function(r,i,a){var s=r[0],c=r[1],h=r[2],l=dt(c);if(s!==n.userId||!e.path.isEqual(l))return void a.done();var f=n.keyForBatchId(h);return It(t).get(f).next(function(t){null===t&&u("Dangling document-mutation reference found: "+r+" which points to "+f),o.push(n.serializer.fromDbMutationBatch(t))})}).next(function(){return o})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;c(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,i=r.length+1,o=kr.prefixForPath(this.userId,r),a=IDBKeyRange.lowerBound(o),s=new wn(B);return St(t).iterate({range:a},function(t,e,o){var a=t[0],u=t[1],c=t[2],h=dt(u);if(a!==n.userId||!r.isPrefixOf(h))return void o.done();h.length===i&&(s=s.add(c))}).next(function(){var e=[],r=[];return s.forEach(function(i){var o=n.keyForBatchId(i);r.push(It(t).get(o).next(function(t){null===t&&u("Dangling document-mutation reference found, which points to "+o),e.push(n.serializer.fromDbMutationBatch(t))}))}),rr.waitFor(r).next(function(){return e})})},t.prototype.removeMutationBatches=function(t,e){for(var n=It(t),r=St(t),i=[],o=this,a=0,s=e;a0,"Removing from an empty query cache"),this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){return kt(t).delete(e.targetId)}).next(function(){return n.metadata.targetCount-=1,n.saveMetadata(t)})},t.prototype.saveMetadata=function(t){return Nt(t).put(Or.key,this.metadata)},t.prototype.saveQueryData=function(t,e){return kt(t).put(this.serializer.toDbTarget(e))},t.prototype.updateMetadataFromQueryData=function(t){var e=!1;return t.targetId>this.metadata.highestTargetId&&(this.metadata.highestTargetId=t.targetId,e=!0),e},Object.defineProperty(t.prototype,"count",{get:function(){return this.metadata.targetCount},enumerable:!0,configurable:!0}),t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return kt(t).iterate({range:i,index:Rr.queryTargetsIndexName},function(t,r,i){var a=n.serializer.fromDbTarget(r);e.isEqual(a.query)&&(o=a,i.done())}).next(function(){return o})},t.prototype.addMatchingKeys=function(t,e,n){var r=[],i=At(t);return e.forEach(function(t){var e=ht(t.path);r.push(i.put(new _r(n,e)))}),rr.waitFor(r)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,i=[],o=At(t);return e.forEach(function(t){var e=ht(t.path);i.push(o.delete([n,e])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(t)}),rr.waitFor(i)},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=At(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return this.notifyGCForRemovedKeys(t,r).next(function(){return n.delete(r)})},t.prototype.notifyGCForRemovedKeys=function(t,e){var n=this,r=At(t);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:e,keysOnly:!0},function(t,e,r){var i=dt(t[1]),o=new ye(i);c(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(o)}):rr.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=At(t),i=rt();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=dt(t[1]),o=new ye(r);i=i.add(o)}).next(function(){return i})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){c(null!==t,"Persistence Transaction cannot be null for query cache containsKey");var n=ht(e.path),r=IDBKeyRange.bound([n],[V(n)],!1,!0),i=0;return At(t).iterate({index:_r.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){i++,n.done()}).next(function(){return i>0})},t}(),Fr=function(){function t(t){this.serializer=t}return t.prototype.addEntry=function(t,e){return _t(t).put(Ot(e.key),this.serializer.toDbRemoteDocument(e))},t.prototype.removeEntry=function(t,e){return _t(t).delete(Ot(e))},t.prototype.getEntry=function(t,e){var n=this;return _t(t).get(Ot(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=et(),i=e.path.toArray(),o=IDBKeyRange.lowerBound(i);return _t(t).iterate({range:o},function(t,i,o){var a=n.serializer.fromDbRemoteDocument(i);e.path.isPrefixOf(a.key.path)?a instanceof ge&&e.matches(a)&&(r=r.insert(a.key,a)):o.done()}).next(function(){return r})},t}(),Vr=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document);if(t.noDocument){var e=ye.fromSegments(t.noDocument.path),n=t.noDocument.readTime,r=new nn(n.seconds,n.nanos);return new ve(e,rn.fromTimestamp(r))}return u("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof ge){var e=this.remoteSerializer.toDocument(t);return new Ar(null,e)}var n=t.key.path.toArray(),r=t.version.toTimestamp(),i=new Ir(r.seconds,r.nanos);return new Ar(new Nr(n,i),null)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new Cr(t,e.batchId,e.localWriteTime.toEpochMilliseconds(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=nn.fromEpochMilliseconds(t.localWriteTimeMs);return new gr(t.batchId,r,n)},t.prototype.fromDbTarget=function(t){var e,n=new nn(t.readTime.seconds,t.readTime.nanos),r=rn.fromTimestamp(n);return e=Mt(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new an(e,t.targetId,De.Listen,r,t.resumeToken)},t.prototype.toDbTarget=function(t){c(De.Listen===t.purpose,"Only queries with purpose "+De.Listen+" may be stored, got "+t.purpose);var e,n=t.snapshotVersion.toTimestamp(),r=new Ir(n.seconds,n.nanos);e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),c("string"==typeof t.resumeToken,"Persisting non-string resume token not supported.");var i=t.resumeToken;return new Rr(t.targetId,t.query.canonicalId(),r,i,0,e)},t}(),Gr="There is another tab open with offline persistence enabled. Only one such tab is allowed at a time. The other tab must be closed or persistence must be disabled.",Qr=function(){function t(e,n){this.ownerId=this.generateOwnerId(),this.dbName=e+t.MAIN_DATABASE,this.serializer=new Vr(n),this.localStoragePrefix=e}return t.prototype.start=function(){var e=this;return t.isAvailable()?(c(!this.started,"IndexedDbPersistence double-started!"),this.started=!0,Lr.openOrCreate(this.dbName,2,pt).then(function(t){e.simpleDb=t}).then(function(){return e.tryAcquireOwnerLease()}).then(function(){e.scheduleOwnerLeaseRefreshes(),e.attachWindowUnloadHook()})):(this.persistenceError=new ie(re.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."),Promise.reject(this.persistenceError))},t.prototype.shutdown=function(){var t=this;return c(this.started,"IndexedDbPersistence shutdown without start!"),this.started=!1,this.detachWindowUnloadHook(),this.stopOwnerLeaseRefreshes(),this.releaseOwnerLease().then(function(){t.simpleDb.close()})},t.prototype.getMutationQueue=function(t){return Ur.forUser(t,this.serializer)},t.prototype.getQueryCache=function(){return new qr(this.serializer)},t.prototype.getRemoteDocumentCache=function(){return new Fr(this.serializer)},t.prototype.runTransaction=function(t,e){var n=this;return this.persistenceError?Promise.reject(this.persistenceError):(o("IndexedDbPersistence","Starting transaction:",t),this.simpleDb.runTransaction("readwrite",Mr,function(t){return n.ensureOwnerLease(t).next(function(){return e(t)})}))},t.isAvailable=function(){return Lr.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.tryAcquireOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[Sr.store],function(e){var n=e.store(Sr.store);return n.get("owner").next(function(e){if(t.validOwner(e))return o("IndexedDbPersistence","Valid owner already. Failing. Current owner:",e),t.persistenceError=new ie(re.FAILED_PRECONDITION,Gr),rr.reject(t.persistenceError);var r=new Sr(t.ownerId,Date.now());return o("IndexedDbPersistence","No valid owner. Acquiring owner lease. Current owner:",e,"New owner:",r),n.put("owner",r)})})},t.prototype.releaseOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[Sr.store],function(e){var n=e.store(Sr.store);return n.get("owner").next(function(e){return null!==e&&e.ownerId===t.ownerId?(o("IndexedDbPersistence","Releasing owner lease."),n.delete("owner")):rr.resolve()})})},t.prototype.ensureOwnerLease=function(t){var e=this;return t.store(Sr.store).get("owner").next(function(t){return null===t||t.ownerId!==e.ownerId?(e.persistenceError=new ie(re.FAILED_PRECONDITION,Gr),rr.reject(e.persistenceError)):rr.resolve()})},t.prototype.validOwner=function(t){var e=Date.now(),n=e-5e3,r=e;return!(null===t||t.leaseTimestampMsr?(a("Persistence owner-lease is in the future. Discarding.",t),1):t.ownerId===this.getZombiedOwnerId()))},t.prototype.scheduleOwnerLeaseRefreshes=function(){var t=this;this.ownerLeaseRefreshHandle=setInterval(function(){t.runTransaction("Refresh owner timestamp",function(e){return e.store(Sr.store).put("owner",new Sr(t.ownerId,Date.now()))}).catch(function(e){a(e),t.stopOwnerLeaseRefreshes()})},4e3)},t.prototype.stopOwnerLeaseRefreshes=function(){this.ownerLeaseRefreshHandle&&(clearInterval(this.ownerLeaseRefreshHandle),this.ownerLeaseRefreshHandle=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;this.windowUnloadHandler=function(){t.setZombiedOwnerId(t.ownerId),t.shutdown()},window.addEventListener("unload",this.windowUnloadHandler)},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.getZombiedOwnerId=function(){try{var t=window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());return o("IndexedDbPersistence","Zombied ownerID from LocalStorage:",t),t}catch(t){return a("Failed to get zombie owner id.",t),null}},t.prototype.setZombiedOwnerId=function(t){try{null===t?window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey()):window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(),t)}catch(t){a("Failed to set zombie owner id.",t)}},t.prototype.zombiedOwnerLocalStorageKey=function(){return this.localStoragePrefix+"zombiedOwnerId"},t.prototype.generateOwnerId=function(){return oe.newId()},t.MAIN_DATABASE="main",t}(),Kr=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.remoteDocumentCache.getEntry(t,e).next(function(r){return n.computeLocalDocument(t,e,r)})},t.prototype.getDocuments=function(t,e){var n=this,r=[],i=tt();return e.forEach(function(e){r.push(n.getDocument(t,e).next(function(t){t||(t=new ve(e,rn.forDeletedDoc())),i=i.insert(e,t)}))}),rr.waitFor(r).next(function(){return i})},t.prototype.getDocumentsMatchingQuery=function(t,e){return ye.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new ye(e)).next(function(t){var e=et();return t instanceof ge&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(e){return r.computeLocalDocuments(t,e)}).next(function(i){return n=i,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(e){for(var i=rt(),o=0,a=e;o0?e.mutationQueue.removeMutationBatches(t,n):rr.resolve()})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations",function(n){var r,i=nn.now();return e.mutationQueue.addMutationBatch(n,i,t).next(function(t){r=t;var i=r.keys();return e.localDocuments.getDocuments(n,i)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch",function(n){var r;return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){if(e.shouldHoldBatchResult(t.commitVersion))return e.heldBatchResults.push(t),r=rt(),rr.resolve();var i=new jr(e.remoteDocuments);return e.releaseBatchResults(n,[t],i).next(function(t){return r=t,i.apply(n)})}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch",function(n){var r,i;return e.mutationQueue.lookupMutationBatch(n,t).next(function(i){return c(null!=i,"Attempt to reject nonexistent batch!"),r=i,e.mutationQueue.getHighestAcknowledgedBatchId(n).next(function(e){return c(t>e,"Acknowledged batches can't be rejected."),r})}).next(function(){return e.removeMutationBatch(n,r)}).next(function(t){return i=t,e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,i)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){return this.queryCache.getLastRemoteSnapshotVersion()},t.prototype.applyRemoteEvent=function(t){var e=this,n=new jr(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event",function(r){var i=[];p(t.targetChanges,function(t,n){var o=e.targetIds[t];if(o){var a=n.mapping;if(a)if(a instanceof Nn)i.push(e.queryCache.removeMatchingKeysForTargetId(r,t).next(function(){return e.queryCache.addMatchingKeys(r,a.documents,t)}));else{if(!(a instanceof An))return u("Unknown mapping type: "+JSON.stringify(a));i.push(e.queryCache.removeMatchingKeys(r,a.removedDocuments,t).next(function(){return e.queryCache.addMatchingKeys(r,a.addedDocuments,t)}))}var s=n.resumeToken;s.length>0&&(o=o.update({resumeToken:s,snapshotVersion:n.snapshotVersion}),e.targetIds[t]=o,i.push(e.queryCache.updateQueryData(r,o)))}});var a=rt();t.documentUpdates.forEach(function(t,s){a=a.add(t),i.push(n.getEntry(r,t).next(function(r){null==r||s.version.isEqual(rn.MIN)||s.version.compareTo(r.version)>=0?n.addEntry(s):o("LocalStore","Ignoring outdated watch update for ",t,". Current version:",r.version," Watch version:",s.version),e.garbageCollector.addPotentialGarbageKey(t)}))});var s=e.queryCache.getLastRemoteSnapshotVersion(),h=t.snapshotVersion;h.isEqual(rn.MIN)||(c(h.compareTo(s)>=0,"Watch stream reverted to previous snapshot?? "+h+" < "+s),i.push(e.queryCache.setLastRemoteSnapshotVersion(r,h)));var l;return rr.waitFor(i).next(function(){return e.releaseHeldBatchResults(r,n)}).next(function(t){return l=t,n.apply(r)}).next(function(){return e.localDocuments.getDocuments(r,a.unionWith(l))})})},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("Notify local view changes",function(n){for(var r=[],i=0,o=t;i0},t.prototype.releaseBatchResults=function(t,e,n){for(var r=this,i=rr.resolve(),o=0,a=e;othis.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged"),o=this.mutationQueue[i];return c(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),c(!o.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,rr.resolve()},t.prototype.getLastStreamToken=function(t){return rr.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,rr.resolve()},t.prototype.addMutationBatch=function(t,e,n){c(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;this.nextBatchId++,this.mutationQueue.length>0&&c(this.mutationQueue[this.mutationQueue.length-1].batchId=n?r=n:r++,rr.resolve(this.getAllLiveMutationBatchesBeforeIndex(r))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new sr(e,0),i=new sr(e,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(t){c(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);c(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),rr.resolve(o)},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this,r=e.path,i=r.length+1,o=r;ye.isDocumentKey(o)||(o=o.child(""));var a=new sr(new ye(o),0),s=new wn(B);this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!r.isPrefixOf(e)&&(e.length===i&&(s=s.add(t.targetOrBatchId)),!0)},a);var u=[];return s.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&u.push(e)}),rr.resolve(u)},t.prototype.removeMutationBatches=function(t,e){var n=e.length;c(n>0,"Should not remove mutations when none exist.");var r=e[0].batchId,i=this.mutationQueue.length,o=this.indexOfExistingBatchId(r,"removed");c(this.mutationQueue[o].batchId===r,"Removed batches must exist in the queue");for(var a=1,s=o+1;a=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return c(n.batchId===t,"If found batch must match"),n.isTombstone()?null:n},t}(),zr=function(){function t(){this.queries=new $n(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=rn.MIN,this.highestTargetId=0,this.references=new ar,this.targetCount=0}return t.prototype.start=function(t){return rr.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.getHighestTargetId=function(){return this.highestTargetId},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,rr.resolve()},t.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e)},t.prototype.addQueryData=function(t,e){return c(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,rr.resolve()},t.prototype.updateQueryData=function(t,e){return c(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),rr.resolve()},t.prototype.removeQueryData=function(t,e){return c(this.targetCount>0,"Removing a target from an empty cache"),c(this.queries.has(e.query),"Removing a non-existent target from the cache"),this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),this.targetCount-=1,rr.resolve()},Object.defineProperty(t.prototype,"count",{get:function(){return this.targetCount},enumerable:!0,configurable:!0}),t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return rr.resolve(n)},t.prototype.addMatchingKeys=function(t,e,n){return this.references.addReferences(e,n),rr.resolve()},t.prototype.removeMatchingKeys=function(t,e,n){return this.references.removeReferences(e,n),rr.resolve()},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),rr.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return rr.resolve(n)},t.prototype.setGarbageCollector=function(t){this.references.setGarbageCollector(t)},t.prototype.containsKey=function(t,e){return this.references.containsKey(t,e)},t}(),Xr=function(){function t(){this.docs=tt()}return t.prototype.addEntry=function(t,e){return this.docs=this.docs.insert(e.key,e),rr.resolve()},t.prototype.removeEntry=function(t,e){return this.docs=this.docs.remove(e),rr.resolve()},t.prototype.getEntry=function(t,e){return rr.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=et(),r=new ye(e.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),a=o.key,s=o.value;if(!e.path.isPrefixOf(a.path))break;s instanceof ge&&e.matches(s)&&(n=n.insert(s.key,s))}return rr.resolve(n)},t}(),Yr=function(){function t(){this.mutationQueues={},this.remoteDocumentCache=new Xr,this.queryCache=new zr,this.started=!1}return t.prototype.start=function(){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return c(!this.started,"MemoryPersistence double-started!"),this.started=!0,[2]})})},t.prototype.shutdown=function(){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return c(this.started,"MemoryPersistence shutdown without start!"),this.started=!1,[2]})})},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Hr,this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e){return o("MemoryPersistence","Starting transaction:",t),e(new Jr).toPromise()},t}(),Jr=function(){function t(){}return t}(),Zr=function(){function t(){this.isEager=!1}return t.prototype.addGarbageSource=function(t){},t.prototype.removeGarbageSource=function(t){},t.prototype.addPotentialGarbageKey=function(t){},t.prototype.collectGarbage=function(t){return rr.resolve(rt())},t}(),$r=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t}();!function(t){t.All="all",t.ListenStreamIdle="listen_stream_idle",t.ListenStreamConnectionBackoff="listen_stream_connection_backoff",t.WriteStreamIdle="write_stream_idle",t.WriteStreamConnectionBackoff="write_stream_connection_backoff",t.OnlineStateTimeout="online_state_timeout"}(cr||(cr={}));var ti,ei=function(){function t(t,e,n,r,i){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new $r,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch(function(t){})}return t.createAndSchedule=function(e,n,r,i,o){var a=Date.now()+r,s=new t(e,n,a,i,o);return s.start(r),s},t.prototype.start=function(t){var e=this;this.timerHandle=setTimeout(function(){return e.handleDelayElapsed()},t)},t.prototype.skipDelay=function(){return this.handleDelayElapsed()},t.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new ie(re.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},t.prototype.handleDelayElapsed=function(){var t=this;this.asyncQueue.enqueue(function(){return null!==t.timerHandle?(t.clearTimeout(),t.op().then(function(e){return t.deferred.resolve(e)})):Promise.resolve()})},t.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},t}(),ni=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.operationInProgress=!1}return t.prototype.enqueue=function(t){var e=this;this.verifyNotFailed();var n=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw a("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(t){return e.operationInProgress=!1,t})});return this.tail=n,n},t.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),c(!this.containsDelayedOperation(t),"Attempted to schedule multiple operations with timer id "+t+".");var i=ei.createAndSchedule(this,t,e,n,function(t){return r.removeDelayedOperation(t)});return this.delayedOperations.push(i),i},t.prototype.verifyNotFailed=function(){this.failure&&u("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},t.prototype.verifyOperationInProgress=function(){c(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return this.enqueue(function(){return Promise.resolve()})},t.prototype.containsDelayedOperation=function(t){return this.delayedOperations.findIndex(function(e){return e.timerId===t})>=0},t.prototype.runDelayedOperationsEarly=function(t){var e=this;return this.drain().then(function(){c(t===cr.All||e.containsDelayedOperation(t),"Attempted to drain to missing operation "+t),e.delayedOperations.sort(function(t,e){return t.targetTimeMs-e.targetTimeMs});for(var n=0,r=e.delayedOperations;n=0,"Delayed operation not found."),this.delayedOperations.splice(e,1)},t}(),ri=function(){function t(t,e,n,r,i){this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.timerPromise=null,this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndRun=function(t){this.cancel();var e=this.currentBaseMs+this.jitterDelayMs();this.currentBaseMs>0&&o("ExponentialBackoff","Backing off for "+e+" ms (base delay: "+this.currentBaseMs+" ms)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,e,t),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},t.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}();!function(t){t[t.Initial=0]="Initial",t[t.Auth=1]="Auth",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff",t[t.Stopped=5]="Stopped"}(ti||(ti={}));var ii,oi=1e3,ai=6e4,si=1.5,ui=function(){function t(t,e,n,r,i){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.inactivityTimerPromise=null,this.stream=null,this.listener=null,this.backoff=new ri(t,e,oi,si,ai),this.state=ti.Initial}return t.prototype.isStarted=function(){return this.state===ti.Backoff||this.state===ti.Auth||this.state===ti.Open},t.prototype.isOpen=function(){return this.state===ti.Open},t.prototype.start=function(t){if(this.state===ti.Error)return void this.performBackoff(t);c(this.state===ti.Initial,"Already started"),this.listener=t,this.auth()},t.prototype.stop=function(){this.isStarted()&&this.close(ti.Stopped)},t.prototype.inhibitBackoff=function(){c(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=ti.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.inactivityTimerPromise&&(this.inactivityTimerPromise=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return this.isOpen()?[2,this.close(ti.Initial)]:[2]})})},t.prototype.cancelIdleCheck=function(){this.inactivityTimerPromise&&(this.inactivityTimerPromise.cancel(),this.inactivityTimerPromise=null)},t.prototype.close=function(t,e){return ne.__awaiter(this,void 0,void 0,function(){var n;return ne.__generator(this,function(r){return c(t===ti.Error||W(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),t!==ti.Error?this.backoff.reset():e&&e.code===re.RESOURCE_EXHAUSTED&&(a(""+e),a("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t,n=this.listener,this.listener=null,t!==ti.Stopped?[2,n.onClose(e)]:[2]})})},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;c(this.state===ti.Initial,"Must be in initial state to auth"),this.state=ti.Auth,this.credentialsProvider.getToken(!1).then(function(e){t.startStream(e)},function(e){t.queue.enqueue(function(){return ne.__awaiter(t,void 0,void 0,function(){var t;return ne.__generator(this,function(n){return this.state!==ti.Stopped?(t=new ie(re.UNKNOWN,"Fetching auth token failed: "+e.message),[2,this.handleStreamClose(t)]):[2]})})})})},t.prototype.startStream=function(t){var e=this;if(this.state!==ti.Stopped){c(this.state===ti.Auth,"Trying to start stream in a non-auth state");var n=function(t,n){e.queue.enqueue(function(){return ne.__awaiter(e,void 0,void 0,function(){return ne.__generator(this,function(e){return this.stream===t?[2,n()]:[2]})})})};if(null!==this.listener){var r=this.startRpc(t);this.stream=r,this.stream.onOpen(function(){n(r,function(){return c(e.state===ti.Auth,"Expected stream to be in state auth, but was "+e.state),e.state=ti.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(r,function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(r,function(){return e.onMessage(t)})})}}},t.prototype.performBackoff=function(t){var e=this;c(this.state===ti.Error,"Should only perform backoff in an error case"),this.state=ti.Backoff,this.backoff.backoffAndRun(function(){return ne.__awaiter(e,void 0,void 0,function(){return ne.__generator(this,function(e){return this.state===ti.Stopped?[2]:(this.state=ti.Initial,this.start(t),c(this.isStarted(),"PersistentStream should have started"),[2])})})})},t.prototype.handleStreamClose=function(t){return c(this.isStarted(),"Can't handle server close on non-started stream"),o("PersistentStream","close with error: "+t),this.stream=null,this.close(ti.Error,t)},t}(),ci=function(t){function e(e,n,r,i){var o=t.call(this,e,cr.ListenStreamConnectionBackoff,cr.ListenStreamIdle,n,r)||this;return o.serializer=i,o}return ne.__extends(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(ui),hi=function(t){function e(e,n,r,i){var o=t.call(this,e,cr.WriteStreamConnectionBackoff,cr.WriteStreamIdle,n,r)||this;return o.serializer=i,o.y=!1,o}return ne.__extends(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.y},enumerable:!0,configurable:!0}),e.prototype.start=function(e){this.y=!1,t.prototype.start.call(this,e)},e.prototype.tearDown=function(){this.y&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(c(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.y){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return c(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.y=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){c(this.isOpen(),"Writing handshake requires an opened stream"),c(!this.y,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;c(this.isOpen(),"Writing mutations requires an opened stream"),c(this.y,"Handshake must be complete before writing mutations"),c(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.sendRequest(n)},e}(ui),li=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}return t.prototype.newPersistentWriteStream=function(){return new hi(this.queue,this.connection,this.credentials,this.serializer)},t.prototype.newPersistentWatchStream=function(){return new ci(this.queue,this.connection,this.credentials,this.serializer)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("Commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults)})},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",n).then(function(n){var r=tt();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var i=[];return t.forEach(function(t){var e=r.get(t);c(!!e,"Missing entity in write response for "+t),i.push(e)}),i})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invokeRPC(t,e,r)})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invokeStreamingRPC(t,e,r)})},t}(),fi=function(){function t(t){this.datastore=t,this.readVersions=nt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e=t.version;t instanceof ve&&(e=rn.forDeletedDoc());var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new ie(re.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){return e.recordVersion(t)}),t})},t.prototype.write=function(t){if(this.committed)throw new ie(re.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?fn.updateTime(e):fn.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.isEqual(rn.forDeletedDoc()))throw new ie(re.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?fn.updateTime(e):fn.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new gn(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,rn.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}(),di=function(){function t(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=Kn.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return t.prototype.handleWatchStreamStart=function(){var t=this;this.setAndBroadcast(Kn.Unknown),null===this.onlineStateTimer&&(this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(cr.OnlineStateTimeout,1e4,function(){return t.onlineStateTimer=null,c(t.state===Kn.Unknown,"Timer should be canceled if we transitioned to a different state."),o("OnlineStateTracker","Watch stream didn't reach online or offline within 10000ms. Considering client offline."),t.logClientOfflineWarningIfNecessary(),t.setAndBroadcast(Kn.Offline),Promise.resolve()}))},t.prototype.handleWatchStreamFailure=function(){this.state===Kn.Online?this.setAndBroadcast(Kn.Unknown):++this.watchStreamFailures>=2&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary(),this.setAndBroadcast(Kn.Offline))},t.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===Kn.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},t.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},t.prototype.logClientOfflineWarningIfNecessary=function(){this.shouldWarnClientIsOffline&&(a("Could not reach Firestore backend."),this.shouldWarnClientIsOffline=!1)},t.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},t}(),pi=function(){function t(t,e,n,r){this.localStore=t,this.datastore=e,this.pendingWrites=[],this.lastBatchSeen=yr,this.listenTargets={},this.pendingTargetResponses={},this.accumulatedWatchChanges=[],this.watchStream=null,this.writeStream=null,this.onlineStateTracker=new di(n,r)}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.isNetworkEnabled=function(){return c(null==this.watchStream==(null==this.writeStream),"WatchStream and WriteStream should both be null or non-null"),null!=this.watchStream},t.prototype.enableNetwork=function(){var t=this;return this.isNetworkEnabled()?Promise.resolve():(this.watchStream=this.datastore.newPersistentWatchStream(),this.writeStream=this.datastore.newPersistentWriteStream(),this.localStore.getLastStreamToken().then(function(e){return t.writeStream.lastStreamToken=e,t.shouldStartWatchStream()?t.startWatchStream():t.onlineStateTracker.set(Kn.Unknown),t.fillWritePipeline()}))},t.prototype.disableNetwork=function(){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return this.disableNetworkInternal(),this.onlineStateTracker.set(Kn.Offline),[2]})})},t.prototype.disableNetworkInternal=function(){this.isNetworkEnabled()&&(this.watchStream.stop(),this.writeStream.stop(),this.cleanUpWatchStreamState(),this.cleanUpWriteStreamState(),this.writeStream=null,this.watchStream=null)},t.prototype.shutdown=function(){return o("RemoteStore","RemoteStore shutting down."),this.disableNetworkInternal(),this.onlineStateTracker.set(Kn.Unknown),Promise.resolve()},t.prototype.listen=function(t){c(!f(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){c(f(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.isNetworkEnabled()&&this.watchStream.isOpen()&&(this.sendUnwatchRequest(t),y(this.listenTargets)&&this.watchStream.markIdle())},t.prototype.sendWatchRequest=function(t){this.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.recordPendingTargetRequest=function(t){this.pendingTargetResponses[t]=(this.pendingTargetResponses[t]||0)+1},t.prototype.startWatchStream=function(){c(this.shouldStartWatchStream(),"startWriteStream() called when shouldStartWatchStream() is false."),this.watchStream.start({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.onlineStateTracker.handleWatchStreamStart()},t.prototype.shouldStartWatchStream=function(){return this.isNetworkEnabled()&&!this.watchStream.isStarted()&&!y(this.listenTargets)},t.prototype.cleanUpWatchStreamState=function(){this.accumulatedWatchChanges=[],this.pendingTargetResponses={}},t.prototype.onWatchStreamOpen=function(){return ne.__awaiter(this,void 0,void 0,function(){var t=this;return ne.__generator(this,function(e){return p(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),[2]})})},t.prototype.onWatchStreamClose=function(t){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return c(this.isNetworkEnabled(),"onWatchStreamClose() should only be called when the network is enabled"),this.cleanUpWatchStreamState(),this.onlineStateTracker.handleWatchStreamFailure(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(Kn.Unknown),[2]})})},t.prototype.onWatchStreamChange=function(t,e){return ne.__awaiter(this,void 0,void 0,function(){var n;return ne.__generator(this,function(r){return this.onlineStateTracker.set(Kn.Online),t instanceof On&&t.state===Cn.Removed&&t.cause?[2,this.handleTargetError(t)]:(this.accumulatedWatchChanges.push(t),!e.isEqual(rn.MIN)&&e.compareTo(this.localStore.getLastRemoteSnapshotVersion())>=0?(n=this.accumulatedWatchChanges,this.accumulatedWatchChanges=[],[2,this.handleWatchChangeBatch(e,n)]):[2])})})},t.prototype.handleWatchChangeBatch=function(t,e){var n=this,r=new Mn(t,this.listenTargets,this.pendingTargetResponses);r.addChanges(e);var i=r.createRemoteEvent();this.pendingTargetResponses=r.pendingTargetResponses;var o=[];return p(r.existenceFilters,function(e,r){var a=n.listenTargets[e];if(a){var s=a.query;if(s.isDocumentQuery())if(0===r.count){var u=new ye(s.path),h=new ve(u,t);i.addDocumentUpdate(h)}else c(1===r.count,"Single document existence filter with count: "+r.count);else{var l=n.localStore.remoteDocumentKeys(e).then(function(t){if(i.targetChanges[e]){var o=i.targetChanges[e].mapping;null!==o&&(o instanceof An?t=o.applyToKeySet(t):(c(o instanceof Nn,"Expected either reset or update mapping but got something else: "+o),t=o.documents))}if(t.size!==r.count){i.handleExistenceFilterMismatch(e);var u=new an(s,e,a.purpose);n.listenTargets[e]=u,n.sendUnwatchRequest(e);var h=new an(s,e,De.ExistenceFilterMismatch);n.sendWatchRequest(h)}});o.push(l)}}}),Promise.all(o).then(function(){return p(i.targetChanges,function(t,e){if(e.resumeToken.length>0){var r=n.listenTargets[t];r&&(n.listenTargets[t]=r.update({resumeToken:e.resumeToken,snapshotVersion:e.snapshotVersion}))}}),n.syncEngine.applyRemoteEvent(i)})},t.prototype.handleTargetError=function(t){var e=this;c(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return ne.__awaiter(e,void 0,void 0,function(){return ne.__generator(this,function(e){return f(this.listenTargets,t)?(delete this.listenTargets[t],[2,this.syncEngine.rejectListen(t,n)]):[2]})})})}),r},t.prototype.cleanUpWriteStreamState=function(){this.lastBatchSeen=yr,o("RemoteStore","Stopping write stream with "+this.pendingWrites.length+" pending writes"),this.pendingWrites=[]},t.prototype.fillWritePipeline=function(){return ne.__awaiter(this,void 0,void 0,function(){var t=this;return ne.__generator(this,function(e){return this.canWriteMutations()?[2,this.localStore.nextMutationBatch(this.lastBatchSeen).then(function(e){if(null!==e)return t.commit(e),t.fillWritePipeline();0===t.pendingWrites.length&&t.writeStream.markIdle()})]:[2]})})},t.prototype.canWriteMutations=function(){return this.isNetworkEnabled()&&this.pendingWrites.length<10},t.prototype.outstandingWrites=function(){return this.pendingWrites.length},t.prototype.commit=function(t){c(this.canWriteMutations(),"commit called when batches can't be written"),this.lastBatchSeen=t.batchId,this.pendingWrites.push(t),this.shouldStartWriteStream()?this.startWriteStream():this.isNetworkEnabled()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.isNetworkEnabled()&&!this.writeStream.isStarted()&&this.pendingWrites.length>0},t.prototype.startWriteStream=function(){c(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})},t.prototype.onWriteStreamOpen=function(){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(t){return this.writeStream.writeHandshake(),[2]})})},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.pendingWrites;e0,"Got result for empty pending writes");var r=this.pendingWrites.shift(),i=vr.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){return ne.__awaiter(this,void 0,void 0,function(){var e,n=this;return ne.__generator(this,function(r){return c(this.isNetworkEnabled(),"onWriteStreamClose() should only be called when the network is enabled"),t&&this.pendingWrites.length>0?(c(!!t,"We have pending writes, but the write stream closed without an error"),e=void 0,e=this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t),[2,e.then(function(){n.shouldStartWriteStream()&&n.startWriteStream()})]):[2]})})},t.prototype.handleHandshakeError=function(t){return ne.__awaiter(this,void 0,void 0,function(){return ne.__generator(this,function(e){return X(t.code)||t.code===re.ABORTED?(o("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=h(),[2,this.localStore.setLastStreamToken(h())]):[2]})})},t.prototype.handleWriteError=function(t){return ne.__awaiter(this,void 0,void 0,function(){var e,n=this;return ne.__generator(this,function(r){return X(t.code)?(e=this.pendingWrites.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,t).then(function(){return n.fillWritePipeline()})]):[2]})})},t.prototype.createTransaction=function(){return new fi(this.datastore)},t.prototype.handleUserChange=function(t){if(o("RemoteStore","RemoteStore changing users: uid=",t.uid),this.isNetworkEnabled())return this.disableNetworkInternal(),this.onlineStateTracker.set(Kn.Unknown),this.enableNetwork()},t}(),mi=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r}return t.prototype.start=function(t){var e=this,n=new $r,r=new $r,i=!1;return this.credentials.setUserChangeListener(function(o){i?e.asyncQueue.enqueue(function(){return e.handleUserChange(o)}):(i=!0,e.initializePersistence(t,r).then(function(){return e.initializeRest(o)}).then(n.resolve,n.reject))}),this.asyncQueue.enqueue(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.enqueue(function(){return t.remoteStore.enableNetwork()})},t.prototype.initializePersistence=function(t,e){var n=this;return t?this.startIndexedDbPersistence().then(e.resolve).catch(function(t){return e.reject(t),n.canFallback(t)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),n.startMemoryPersistence()):Promise.reject(t)}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t.code===re.FAILED_PRECONDITION||t.code===re.UNIMPLEMENTED},t.prototype.startIndexedDbPersistence=function(){this.garbageCollector=new Zr;var t=Qr.buildStoragePrefix(this.databaseInfo),e=new Pn(this.databaseInfo.databaseId,{useProto3Json:!0});return this.persistence=new Qr(t,e),this.persistence.start()},t.prototype.startMemoryPersistence=function(){return this.garbageCollector=new ir,this.persistence=new Yr,this.persistence.start()},t.prototype.initializeRest=function(t){var e=this;return this.platform.loadConnection(this.databaseInfo).then(function(n){e.localStore=new Wr(e.persistence,t,e.garbageCollector);var r=e.platform.newSerializer(e.databaseInfo.databaseId),i=new li(e.asyncQueue,n,e.credentials,r),o=function(t){e.syncEngine.applyOnlineStateChange(t),e.eventMgr.applyOnlineStateChange(t)};return e.remoteStore=new pi(e.localStore,i,e.asyncQueue,o),e.syncEngine=new mr(e.localStore,e.remoteStore,t),e.remoteStore.syncEngine=e.syncEngine,e.eventMgr=new er(e.syncEngine),e.localStore.start()}).then(function(){return e.remoteStore.start()})},t.prototype.handleUserChange=function(t){return this.asyncQueue.verifyOperationInProgress(),o("FirestoreClient","User Changed: "+t.uid),this.syncEngine.handleUserChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.enqueue(function(){return t.remoteStore.disableNetwork()})},t.prototype.shutdown=function(){var t=this;return this.asyncQueue.enqueue(function(){return t.credentials.removeUserChangeListener(),t.remoteStore.shutdown()}).then(function(){return t.persistence.shutdown()})},t.prototype.listen=function(t,e,n){var r=this,i=new nr(t,e,n);return this.asyncQueue.enqueue(function(){return r.eventMgr.listen(i)}),i},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.enqueue(function(){return e.eventMgr.unlisten(t)})},t.prototype.write=function(t){var e=this,n=new $r;return this.asyncQueue.enqueue(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.enqueue(function(){return ne.__awaiter(e,void 0,void 0,function(){return ne.__generator(this,function(t){return[2]})})}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),yi=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),gi=function(){function t(t){this.uid=t}return t.prototype.isAuthenticated=function(){return null!=this.uid},t.prototype.toKey=function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"},t.prototype.isEqual=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),vi=function(){function t(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}return t}(),bi=function(){function t(){this.userListener=null}return t.prototype.getToken=function(t){return Promise.resolve(null)},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,t(gi.UNAUTHENTICATED)},t.prototype.removeUserChangeListener=function(){c(null!==this.userListener,"removeUserChangeListener() when no listener registered"),this.userListener=null},t}(),wi=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.userCounter=0,this.userListener=null,this.tokenListener=function(){var t=e.getUser();e.currentUser&&t.isEqual(e.currentUser)||(e.currentUser=t,e.userCounter++,e.userListener&&e.userListener(e.currentUser))},this.userCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(t){var e=this;c(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.userCounter;return this.app.INTERNAL.getToken(t).then(function(t){if(e.userCounter!==n)throw new ie(re.ABORTED,"getToken aborted due to uid change.");return t?(c("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new vi(t.accessToken,e.currentUser)):null})},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeUserChangeListener=function(){c(null!=this.tokenListener,"removeUserChangeListener() called twice"),c(null!==this.userListener,"removeUserChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.userListener=null},t.prototype.getUser=function(){"function"!=typeof this.app.INTERNAL.getUid&&u("This version of the Firestore SDK requires at least version 3.7.0 of firebase.js.");var t=this.app.INTERNAL.getUid();return c(null===t||"string"==typeof t,"Received invalid UID: "+t),new gi(t)},t}(),Ei=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=gi.FIRST_PARTY,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),Ti=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(t){return Promise.resolve(new Ei(this.gapi,this.sessionIndex))},t.prototype.setUserChangeListener=function(t){t(gi.FIRST_PARTY)},t.prototype.removeUserChangeListener=function(){},t}(),Ii=function(){function t(){}return t.delete=function(){return Si.instance},t.serverTimestamp=function(){return Di.instance},t.prototype.isEqual=function(t){return this===t},t}(),Si=function(t){function e(){return t.call(this)||this}return ne.__extends(e,t),e.instance=new e,e}(Ii),Di=function(t){function e(){return t.call(this)||this}return ne.__extends(e,t),e.instance=new e,e}(Ii),Ci=l(Ii,"Use FieldValue.() instead."),ki=/^__.*__$/,Ni=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new mn(t,this.data,this.fieldMask,e)):n.push(new pn(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new yn(t,this.fieldTransforms)),n},t}(),Ai=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new mn(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new yn(t,this.fieldTransforms)),n},t}();!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.QueryValue=3]="QueryValue"}(ii||(ii={}));var Ri=function(){function t(t,e,n,r,i,o){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===i&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=i||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path+")";return new ie(re.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() can only be used with update() and set() with {merge:true}")}if(t instanceof Di){if(!Bt(e.dataSource))throw e.createError("FieldValue.serverTimestamp() can only be used with set() and update()");if(null===e.path)throw e.createError("FieldValue.serverTimestamp() is not currently supported inside arrays");return e.fieldTransforms.push(new cn(e.path,un.instance)),null}return u("Unknown FieldValue type: "+t)}throw e.createError("Unsupported field value: "+R(t))},t}(),Mi="firestore.googleapis.com",Li=!0,xi=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new ie(re.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Mi,this.ssl=Li}else S("settings","string","host",t.host),this.host=t.host,D("settings","boolean","ssl",t.ssl),this.ssl=d(t.ssl,Li);M("settings",t,["host","ssl","credentials"]),D("settings","object","credentials",t.credentials),this.credentials=t.credentials}return t.prototype.isEqual=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials},t}(),Pi=function(){function t(){}return t}(),Bi=function(){function t(e){var n=this;this.k=new ni,this.INTERNAL={delete:function(){return ne.__awaiter(n,void 0,void 0,function(){return ne.__generator(this,function(t){return this._?[2,this._.shutdown()]:[2]})})}};var r=new Pi;if("object"==typeof e.options){var i=e;r.firebaseApp=i,r.databaseId=t.databaseIdFromApp(i),r.persistenceKey=r.firebaseApp.name,r.credentials=new wi(i)}else{var o=e;if(!o.projectId)throw new ie(re.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new le(o.projectId,o.database),r.persistenceKey="[DEFAULT]",r.credentials=new bi}r.settings=new xi({}),this.x=r,this._databaseId=r.databaseId}return t.prototype.settings=function(t){if(v("Firestore.settings",arguments,1),T("Firestore.settings","object",1,t),f(t,"persistence"))throw new ie(re.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new xi(t);if(this._&&!this.x.settings.isEqual(e))throw new ie(re.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this.x.settings=e,void 0!==e.credentials&&(this.x.credentials=Lt(e.credentials))},t.prototype.enableNetwork=function(){return this.ensureClientConfigured(),this._.enableNetwork()},t.prototype.disableNetwork=function(){return this.ensureClientConfigured(),this._.disableNetwork()},t.prototype.enablePersistence=function(){if(this._)throw new ie(re.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");return this.configureClient(!0)},t.prototype.ensureClientConfigured=function(){return this._||this.configureClient(!1),this._},t.prototype.configureClient=function(t){var e=this;c(!!this.x.settings.host,"FirestoreSettings.host cannot be falsey"),c(!this._,"configureClient() called multiple times");var n=new ce(this.x.databaseId,this.x.persistenceKey,this.x.settings.host,this.x.settings.ssl),r=function(t){if(t instanceof Fi){var n=e.x.databaseId,r=t.firestore.x.databaseId;if(!r.isEqual(n))throw new ie(re.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new _i(e.x.databaseId,t.q)}return t};return this._dataConverter=new Oi(r),this._=new mi(ee.getPlatform(),n,this.x.credentials,this.k),this._.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!f(e,"projectId")){if(f(e,"firestoreId"))throw new ie(re.INVALID_ARGUMENT,'"firestoreId" is now specified as "projectId" in firebase.initializeApp.');throw new ie(re.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')}if(f(e,"firestoreOptions"))throw new ie(re.INVALID_ARGUMENT,'"firestoreOptions" values are now specified with Firestore.settings()');var n=e.projectId;if(!n||"string"!=typeof n)throw new ie(re.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new le(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this.x.firebaseApp)throw new ie(re.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this.x.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("Firestore.collection",arguments,1),T("Firestore.collection","string",1,t),!t)throw new ie(re.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new Wi(de.fromString(t),this)},t.prototype.doc=function(t){if(v("Firestore.doc",arguments,1),T("Firestore.doc","string",1,t),!t)throw new ie(re.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),Fi.forPath(de.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return v("Firestore.runTransaction",arguments,1),T("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Ui(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new qi(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(r()){case Yt.DEBUG:return"debug";case Yt.ERROR:return"error";case Yt.SILENT:return"silent";default:return u("Unknown log level: "+r())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(v("Firestore.setLogLevel",arguments,1),T("Firestore.setLogLevel","string",1,t),t){case"debug":i(Yt.DEBUG);break;case"error":i(Yt.ERROR);break;case"silent":i(Yt.SILENT);break;default:throw new ie(re.INVALID_ARGUMENT,"Invalid log level: "+t)}},t}(),Ui=function(){function t(t,e){this.Q=t,this.z=e}return t.prototype.get=function(t){var e=this;v("Transaction.get",arguments,1);var n=jt("Transaction.get",t,this.Q);return this.z.lookup([n.q]).then(function(t){if(!t||1!==t.length)return u("Mismatch in docs returned from document lookup.");var r=t[0];return r instanceof ve?new Gi(e.Q,n.q,null,!1):new Gi(e.Q,n.q,r,!1)})},t.prototype.set=function(t,e,n){w("Transaction.set",arguments,2,3);var r=jt("Transaction.set",t,this.Q);n=Qt("Transaction.set",n);var i=n.merge?this.Q._dataConverter.parseMergeData("Transaction.set",e):this.Q._dataConverter.parseSetData("Transaction.set",e);return this.z.set(r.q,i),this},t.prototype.update=function(t,e,n){for(var r=[],i=3;i0?[2,this.Q.ensureClientConfigured().write(this.tt)]:[2]})})},t.prototype.verifyNotCommitted=function(){if(this.et)throw new ie(re.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Fi=function(){function t(t,e){this.q=t,this.firestore=e,this._=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new ie(re.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new ye(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this.q.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new Wi(this.q.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.q.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("DocumentReference.collection",arguments,1),T("DocumentReference.collection","string",1,t),!t)throw new ie(re.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=de.fromString(t);return new Wi(this.q.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw L("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this.q.isEqual(e.q)},t.prototype.set=function(t,e){w("DocumentReference.set",arguments,1,2),e=Qt("DocumentReference.set",e);var n=e.merge?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._.write(n.toMutations(this.q,fn.NONE))},t.prototype.update=function(t,e){for(var n=[],r=2;r0)throw new ie(re.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new ie(re.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,i.nt,r)}var o=[e].concat(n);return this.boundFromFields(t,o,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this.it.orderBy;ir.length)throw new ie(re.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],o=0;o, or >=) must be on the same field. But you have inequality filters on '"+e+"' and '"+t.field+"'");var n=this.it.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}},t.prototype.validateNewOrderBy=function(t){if(null===this.it.getFirstOrderByField()){var e=this.it.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new ie(re.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t+"' and so you must also use '"+t+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e+"' instead.")},t}(),ji=function(){function t(t,e,n){this.Q=t,this.ot=e,this.at=n,this._cachedChanges=null,this.metadata=new Vi(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this.at.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.at.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;w("QuerySnapshot.forEach",arguments,1,2),T("QuerySnapshot.forEach","function",1,t),this.at.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new Ki(this.ot,this.Q)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"docChanges",{get:function(){return this._cachedChanges||(this._cachedChanges=Wt(this.Q,this.at)),this._cachedChanges},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){if(!(e instanceof t))throw L("isEqual","QuerySnapshot",1,e);return this.Q===e.Q&&this.ot.isEqual(e.ot)&&this.at.isEqual(e.at)},t.prototype.convertToDocumentImpl=function(t){return new Qi(this.Q,t.key,t,this.metadata.fromCache)},t}(),Wi=function(t){function e(e,n){var r=t.call(this,je.atPath(e),n)||this;if(e.length%2!=1)throw new ie(re.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return ne.__extends(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.it.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.it.path.popLast();return t.isEmpty()?null:new Fi(new ye(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.it.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(w("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=oe.newId()),T("CollectionReference.doc","string",1,t),""===t)throw new ie(re.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=de.fromString(t);return Fi.forPath(this.it.path.child(e),this.firestore)},e.prototype.add=function(t){v("CollectionReference.add",arguments,1),T("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(Ki),Hi=l(Bi,"Use firebase.firestore() instead."),zi=l(Ui,"Use firebase.firestore().runTransaction() instead."),Xi=l(qi,"Use firebase.firestore().batch() instead."),Yi=l(Fi,"Use firebase.firestore().doc() instead."),Ji=l(Gi),Zi=l(Qi),$i=l(Ki),to=l(ji),eo=l(Wi,"Use firebase.firestore().collection() instead."),no={Firestore:Hi,GeoPoint:ue,Blob:se,Transaction:zi,WriteBatch:Xi,DocumentReference:Yi,DocumentSnapshot:Ji,Query:$i,QueryDocumentSnapshot:Zi,QuerySnapshot:to,CollectionReference:eo,FieldPath:jn,FieldValue:Ci,setLogLevel:Bi.setLogLevel};e.registerFirestore=Xt,Xt(Jt.default)},117:function(module,exports,__webpack_require__){(function(global){(function(){function l(t){return"string"==typeof t}function aa(){}function ba(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function n(t){return"array"==ba(t)}function ca(t){var e=ba(t);return"array"==e||"object"==e&&"number"==typeof t.length}function da(t){return"function"==ba(t)}function ea(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}function ha(t,e,n){return t.call.apply(t.bind,arguments)}function ia(t,e,n){if(!t)throw Error();if(2e?null:l(t)?t.charAt(e):t[e]}function ua(t){if(!n(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function va(t){return Array.prototype.concat.apply([],arguments)}function wa(t){var e=t.length;if(0e?1:0}function x(t){return-1!=w.indexOf(t)}function Ca(t,e,n){for(var r in t)e.call(n,t[r],r,t)}function Da(t){var e,n=[],r=0;for(e in t)n[r++]=t[e];return n}function Ea(t){var e,n=[],r=0;for(e in t)n[r++]=e;return n}function Fa(t){var e,n={};for(e in t)n[e]=t[e];return n}function Ha(t,e){for(var n,r,i=1;ir.keyCode||void 0!=r.returnValue)){t:{var i=!1;if(0==r.keyCode)try{r.keyCode=-1;break t}catch(t){i=!0}(i||void 0==r.returnValue)&&(r.returnValue=!0)}for(r=[],i=e.a;i;i=i.parentNode)r.push(i);for(t=t.type,i=r.length-1;0<=i;i--){e.a=r[i];var o=xb(r[i],t,!0,e);n=n&&o}for(i=0;ie.b&&(e.b++,t.next=e.a,e.a=t)}Wb=!1}function Xb(t,e){A.call(this),this.b=t||1,this.a=e||k,this.c=q(this.lb,this),this.g=r()}function Yb(t){t.ea=!1,t.O&&(t.a.clearTimeout(t.O),t.O=null)}function Zb(t,e,n){if(da(t))n&&(t=q(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=q(t.handleEvent,t)}return 2147483647<+e?-1:k.setTimeout(t,e||0)}function $b(t,e,n){u.call(this),this.f=null!=n?q(t,n):t,this.c=e,this.b=q(this.fb,this),this.a=[]}function ac(t){t.Y=Zb(t.b,t.c),t.f.apply(null,t.a)}function bc(t){u.call(this),this.b=t,this.a={}}function dc(t,e,r,i){n(r)||(r&&(cc[0]=""+r),r=cc);for(var o=0;oo.length)){var a=o[1];if(n(a)&&!(1>a.length)){var s=a[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var u=1;ue||3==e&&!Na&&!t.a.V())){t.B||4!=e||7==n||zc(8==n||0>=r?3:2),ad(t);var i=t.a.W();t.C=i,(n=t.a.V())||G(t.b,function(){return"No response text for uri "+t.g+" status "+i}),t.f=200==i,uc(t.b,t.o,t.g,t.c,t.T,e,i),t.f?((r=bd(t))&&(F(t.b,t.c,r,"Initial handshake response via X-HTTP-Initial-Response"),t.v=!0,cd(t,r)),t.K?(dd(t,e,n),Na&&t.f&&3==e&&ed(t)):(F(t.b,t.c,n,null),cd(t,n)),4==e&&fd(t),t.f&&!t.B&&(4==e?t.i.ta(t):(t.f=!1,Yc(t)))):(400==i&&0e.length?Tc:(e=e.substr(r,n),t.G=r+n,e))}function Yc(t){t.U=r()+t.R,jd(t,t.R)}function jd(t,e){if(null!=t.s)throw Error("WatchDog timer not null");t.s=Dc(q(t.gb,t),e)}function ad(t){t.s&&(k.clearTimeout(t.s),t.s=null)}function gd(t){t.i.Ka()||t.B||t.i.ta(t)}function fd(t){ad(t);var e=t.I;e&&"function"==typeof e.$&&e.$(),t.I=null,Yb(t.S),ec(t.L),t.a&&(e=t.a,t.a=null,e.abort(),e.$())}function cd(t,e){try{t.i.Na(t,e),zc(4)}catch(e){xc(t.b,e,"Error in httprequest callback")}}function kd(t){if(t.A&&"function"==typeof t.A)return t.A();if(l(t))return t.split("");if(ca(t)){for(var e=[],n=t.length,r=0;r2*t.c&&md(t),!0)}function md(t){if(t.c!=t.a.length){for(var e=0,n=0;ee)throw Error("Bad port number "+e);t.i=e}else t.i=null}function ud(t,e,n){e instanceof xd?(t.c=e,Dd(t.c,t.h)):(n||(e=yd(e,Ed)),t.c=new xd(e,t.h))}function R(t,e,n){t.c.set(e,n)}function Zc(t,e,r){n(r)||(r=[r+""]),Fd(t.c,e,r)}function Vc(t){return R(t,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^r()).toString(36)),t}function Gd(t){return t instanceof Q?M(t):new Q(t,void 0)}function Hd(t,e,n,r){var i=new Q(null,void 0);return t&&rd(i,t),e&&sd(i,e),n&&td(i,n),r&&(i.a=r),i}function wd(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function yd(t,e,n){return l(t)?(t=encodeURI(t).replace(e,Id),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Id(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function xd(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function S(t){t.a||(t.a=new O,t.b=0,t.c&&qd(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function Kd(t,e){S(t),e=Jd(t,e),P(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,od(t.a,e))}function Ld(t,e){return S(t),e=Jd(t,e),P(t.a.b,e)}function Fd(t,e,n){Kd(t,e),0=t.f}function de(t,e){return t.b?t=t.b==e:t.a?(e=Xd(e),t=P(t.a.a.b,e)):t=!1,t}function be(t,e){t.a?t.a.add(e):t.b=e}function ee(t,e){if(t.b&&t.b==e)t.b=null;else{var n;(n=t.a)&&(n=Xd(e),n=P(t.a.a.b,n)),n&&od(t.a.a,Xd(e))}}function fe(t){if(null!=t.b)return t.c.concat(t.b.u);if(null!=t.a&&0!=t.a.a.c){var e=t.c;return ra(t.a.A(),function(t){e=e.concat(t.u)}),e}return wa(t.c)}function ge(t,e){t.c=t.c.concat(e)}function he(){}function ie(){this.a=new he}function je(t,e,n){var r=n||"";try{ld(t,function(t,n){var i=t;ea(t)&&(i=Db(t)),e.push(r+n+"="+encodeURIComponent(i))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}}function ke(t,e){var n=new sc;G(n,"TestLoadImage: loading "+t);var r=new Image;r.onload=ja(le,n,r,"TestLoadImage: loaded",!0,e),r.onerror=ja(le,n,r,"TestLoadImage: error",!1,e),r.onabort=ja(le,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=ja(le,n,r,"TestLoadImage: timeout",!1,e),k.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}function le(t,e,n,r,i){try{G(t,n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(e){xc(t,e)}}function T(t){A.call(this),this.headers=new O,this.D=t||null,this.c=!1,this.v=this.a=null,this.K=this.u="",this.j=0,this.g="",this.h=this.I=this.s=this.G=!1,this.l=0,this.B=null,this.L=me,this.C=this.o=!1}function re(t){return y&&Va(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}function ta(t){return"content-type"==t.toLowerCase()}function pe(t,e){t.c=!1,t.a&&(t.h=!0,t.a.abort(),t.h=!1),t.g=e,t.j=5,se(t),te(t)}function se(t){t.G||(t.G=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function ue(t){if(t.c&&void 0!==goog)if(t.v[1]&&4==N(t)&&2==t.W())D(t.b,U(t,"Local request error detected and ignored"));else if(t.s&&4==N(t))Zb(t.Ma,0,t);else if(t.dispatchEvent("readystatechange"),4==N(t)){D(t.b,U(t,"Request complete")),t.c=!1;try{var e=t.W();t:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var n=!0;break t;default:n=!1}var r;if(!(r=n)){var i;if(i=0===e){var o=(t.u+"").match(pd)[1]||null;if(!o&&k.self&&k.self.location){var a=k.self.location.protocol;o=a.substr(0,a.length-1)}i=!ne.test(o?o.toLowerCase():"")}r=i}r?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.j=6,t.g=t.Ga()+" ["+t.W()+"]",se(t))}finally{te(t)}}}function te(t,e){if(t.a){qe(t);var n=t.a,r=t.v[0]?aa:null;t.a=null,t.v=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&t.log(ic,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}}function qe(t){t.a&&t.C&&(t.a.ontimeout=null),t.B&&(k.clearTimeout(t.B),t.B=null)}function N(t){return t.a?t.a.readyState:0}function hd(t,e){return t.a?t.a.getResponseHeader(e):null}function U(t,e){return e+" ["+t.K+" "+t.u+" "+t.W()+"]"}function ve(t){var e="";return Ca(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}function we(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=ve(n),l(t)){if(e=encodeURIComponent(e+""),n=null!=n?"="+encodeURIComponent(n+""):"",e+=n){if(n=t.indexOf("#"),0>n&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var i=""}else i=t.substring(r+1,n);t=[t.substr(0,r),i,t.substr(n)],n=t[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return R(t,e,n),t}function xe(t){this.xa=0,this.g=[],this.a=new sc,this.I=new Vd,this.X=this.ua=this.D=this.ja=this.b=this.K=this.j=this.U=this.h=this.L=this.i=null,this.Va=this.R=0,this.Ua=t&&t.Eb||!1,this.ka=this.C=this.s=this.l=this.m=this.f=null,this.u=this.wa=this.N=-1,this.T=this.B=this.v=0,this.G=void 0,this.S=t&&t.supportsCrossDomainXhr||!1,this.J="",this.c=new Zd(t&&t.concurrentRequestLimit),this.la=new ie,this.o=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,(this.va=t&&t.fastHandshake||!1)&&!this.o&&(C(this.a.a,"Force backgroundChannelTest when fastHandshake is enabled."),this.o=!0),t&&t.Ea&&this.a.Ea()}function ye(t){if(G(t.a,"disconnect()"),ze(t),3==t.F){var e=t.R++,n=M(t.D);R(n,"SID",t.J),R(n,"RID",e),R(n,"TYPE","terminate"),Ae(t,n),e=new L(t,t.a,e,void 0),e.J=2,e.h=Vc(M(n)),n=!1,k.navigator&&k.navigator.sendBeacon&&(n=k.navigator.sendBeacon(""+e.h,"")),!n&&k.Image&&((new Image).src=e.h,n=!0),n||(e.a=e.i.ca(null),e.a.fa(e.h)),e.D=r(),Yc(e)}Be(t)}function ze(t){t.C&&(t.C.abort(),t.C=null),t.b&&(t.b.cancel(),t.b=null),t.l&&(k.clearTimeout(t.l),t.l=null),Ce(t),t.c.cancel(),t.m&&(k.clearTimeout(t.m),t.m=null)}function De(t,e){1e3==t.g.length&&H(t.a,function(){return"Already have 1000 queued maps upon queueing "+Db(e)}),t.g.push(new Yd(t.Va++,e)),3==t.F&&Ee(t)}function Ee(t){ce(t.c)||t.m||(t.m=Dc(q(t.Pa,t),0),t.v=0)}function Fe(t,e){var n=t.c;return(n.b?1:n.a?n.a.a.c:0)>=t.c.f-(t.m?1:0)?(H(t.a,"Unexpected retry request is scheduled."),!1):t.m?(G(t.a,"Use the retry request that is already scheduled."),t.g=e.u.concat(t.g),!0):!(1==t.F||2==t.F||t.v>=(t.Ua?0:2)||(G(t.a,"Going to retry POST"),t.m=Dc(q(t.Pa,t,e),Ge(t,t.v)),t.v++,0))}function Ie(t,e){var n;n=e?e.c:t.R++;var r=M(t.D);R(r,"SID",t.J),R(r,"RID",n),R(r,"AID",t.N),Ae(t,r),t.h&&t.i&&we(r,t.h,t.i),n=new L(t,t.a,n,t.v+1),null===t.h&&(n.j=t.i),e&&(t.g=e.u.concat(t.g)),e=He(t,n),n.setTimeout(1e4+Math.round(1e4*Math.random())),be(t.c,n),Uc(n,r,e)}function Ae(t,e){t.f&&ld({},function(t,n){R(e,n,t)})}function He(t,e){var n=Math.min(t.g.length,1e3),r=t.f?q(t.f.Wa,t.f,t):null;t:for(var i=t.g,o=-1;;){var a=["count="+n];-1==o?0(c-=o))o=Math.max(0,i[u].a-100),s=!1;else try{je(h,a,"req"+c+"_")}catch(t){r&&r(h)}}if(s){r=a.join("&");break t}}return t=t.g.splice(0,n),e.u=t,r}function Je(t){if(!t.b&&!t.l){t.T=1;var e=t.Oa;Tb||Ub(),Wb||(Tb(),Wb=!0),Pb.add(e,t),t.B=0}}function Ke(t){return t.b||t.l?(H(t.a,"Request already in progress"),!1):!(3<=t.B||(G(t.a,"Going to retry GET"),t.T++,t.l=Dc(q(t.Oa,t),Ge(t,t.B)),t.B++,0))}function Sd(t,e,n){G(t.a,"Test Connection Finished");var r=e.l;r&&ae(t.c,r),t.ka=n,t.u=e.f,G(t.a,"connectChannel_()"),t.D=Le(t,t.ja),Ee(t)}function Ud(t,e){G(t.a,"Test Connection Failed"),t.u=e.f,V(t,2)}function Ce(t){null!=t.s&&(k.clearTimeout(t.s),t.s=null)}function Ge(t,e){var n=5e3+Math.floor(1e4*Math.random());return t.qa()||(G(t.a,"Inactive channel"),n*=2),n*e}function V(t,e){if(E(t.a,"Error code "+e),2==e){var n=null;t.f&&(n=null);var r=q(t.kb,t);n||(n=new Q("//www.google.com/images/cleardot.gif"),k.location&&"http"==k.location.protocol||rd(n,"https"),Vc(n)),ke(""+n,r)}else K(2);G(t.a,"HttpChannel: error - "+e),t.F=0,t.f&&t.f.Aa(e),Be(t),ze(t)}function Be(t){if(t.F=0,t.u=-1,t.f){var e=fe(t.c);0==e.length&&0==t.g.length||(G(t.a,function(){return"Number of undelivered maps, pending: "+e.length+", outgoing: "+t.g.length}),t.c.c.length=0,wa(t.g),t.g.length=0),t.f.za()}}function Le(t,e){return e=Me(t,null,e),G(t.a,"GetForwardChannelUri: "+e),e}function Td(t,e,n){return e=Me(t,t.ia()?e:null,n),G(t.a,"GetBackChannelUri: "+e),e}function Me(t,e,n){var r=Gd(n);if(""!=r.b)e&&sd(r,e+"."+r.b),td(r,r.i);else{var i,o=k.location;i=e?e+"."+o.hostname:o.hostname,r=Hd(o.protocol,i,o.port,n)}return t.U&&Ca(t.U,function(t,e){R(r,e,t)}),e=t.j,n=t.K,e&&n&&R(r,e,n),R(r,"VER",t.na),Ae(t,r),r}function Ne(){}function Oe(t){for(var e=arguments[0],n=1;nthis.c)throw Error(Ye);this.a=new Ue,this.b=new Wd,this.g=null,this.aa()}function $e(t){if("function"==typeof t.$)t.$();else for(var e in t)t[e]=null}function Ze(t){return We(t.a)+t.b.a.c}function af(t,e){this.a=t,this.b=e}function bf(t){if(this.a=[],t)t:{if(t instanceof bf){var e=t.M();if(t=t.A(),0>=this.a.length){for(var n=this.a,r=0;r>1,t[r].a>n.a);)t[e]=t[r],e=r;t[e]=n}function df(){bf.call(this)}function Y(t,e){this.f=new df,Xe.call(this,t,e)}function Z(t,e,n,r){this.l=t,this.j=!!r,Y.call(this,e,n)}var g,goog=goog||{},k=this,p="closure_uid_"+(1e9*Math.random()>>>0),fa=0,r=Date.now||function(){return+new Date};t(ka,Error),ka.prototype.name="CustomError",t(la,ka),la.prototype.name="AssertionError";var na=0,pa={};u.prototype.i=!1,u.prototype.$=function(){if(!this.i&&(this.i=!0,this.w(),0!=na)){var t=this[p]||(this[p]=++fa);if(0!=na&&this.m&&0parseFloat(Sa)){Ra=Ua+"";break t}}Ra=Sa}var Ka={},Wa,Xa=k.document;Wa=Xa&&y?Qa()||("CSS1Compat"==Xa.compatMode?parseInt(Ra,10):5):void 0;var Ya=Object.freeze||function(t){return t},Za=!y||9<=+Wa,$a=y&&!Va("9"),ab=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return k.addEventListener("test",aa,e),k.removeEventListener("test",aa,e),t}();z.prototype.b=function(){this.Qa=!1},t(bb,z);var cb=Ya({2:"touch",3:"pen",4:"mouse"});bb.prototype.b=function(){bb.H.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,$a)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var db="closure_listenable_"+(1e6*Math.random()|0),eb=0;hb.prototype.add=function(t,e,n,r,i){var o=""+t;(t=this.a[o])||(t=this.a[o]=[],this.b++);var a=ib(t,e,r,i);return-1>>0);t(A,u),A.prototype[db]=!0,g=A.prototype,g.addEventListener=function(t,e,n,r){nb(this,t,e,n,r)},g.removeEventListener=function(t,e,n,r){vb(this,t,e,n,r)},g.dispatchEvent=function(t){var e,n=this.J;if(n)for(e=[];n;n=n.J)e.push(n);n=this.N;var r=t.type||t;if(l(t))t=new z(t,n);else if(t instanceof z)t.target=t.target||n;else{var i=t;t=new z(r,n),Ha(t,i)}if(i=!0,e)for(var o=e.length-1;0<=o;o--){var a=t.a=e[o];i=Ab(a,r,!0,t)&&i}if(a=t.a=n,i=Ab(a,r,!0,t)&&i,i=Ab(a,r,!1,t)&&i,e)for(o=0;o=nc(this).value)for(da(e)&&(e=e()),t=new fc(t,e+"",this.f),n&&(t.a=n),n=this;n;)n=n.a};var oc={},pc=null;sc.prototype.Ea=function(){this.b=!1};var J=new A;t(yc,z),t(Ac,z),t(Bc,z);var Ec={NO_ERROR:0,mb:1,tb:2,sb:3,pb:4,rb:5,ub:6,Sa:7,TIMEOUT:8,xb:9},Fc={ob:"complete",Bb:"success",Ta:"error",Sa:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",qb:"downloadprogress",Cb:"uploadprogress"},Hc={OPEN:"a",nb:"b",Ta:"c",wb:"d"};t(Ic,z),t(Jc,z),Kc.prototype.a=null;var Nc;t(Oc,Kc),Nc=new Oc;var Qc=45e3,Sc={},Tc={};g=L.prototype,g.setTimeout=function(t){this.R=t},g.ib=function(t){t=t.target;var e=this.I;e&&3==N(t)?(G(this.b,"Throttling readystatechange."),e.Ya()):this.Ra(t)},g.Ra=function(t){try{t==this.a?$c(this):C(this.b.a,"Called back with an unexpected xmlhttp")}catch(t){if(G(this.b,"Failed call to OnXmlHttpReadyStateChanged_"),this.a&&this.a.V()){var e=this;xc(this.b,t,function(){return"ResponseText: "+e.a.V()})}else xc(this.b,t,"No response text")}},g.hb=function(){if(this.a){var t=N(this.a),e=this.a.V();this.Ge&&this.ka&&0==this.B&&!this.s&&(this.s=Dc(q(this.cb,this),6e3)));else G(this.a,"Bad POST response data returned"),V(this,11)}else if((t.v||this.b==t)&&Ce(this),!xa(e))for(e=r=this.la.a.parse(e),r=0;rt-this.g)){for(var e;0this.c&&0=i)o=void 0;else{if(1==i)ua(r);else{r[0]=r.pop(),r=0,n=n.a,i=n.length;for(var a=n[r];r>1;){var s=2*r+1,u=2*r+2;if(s=ua.a)break;n[r]=n[s],r=s}n[r]=a}o=o.b}o.apply(this,[e])}},g.ma=function(t){Y.H.ma.call(this,t),this.ra()},g.aa=function(){Y.H.aa.call(this),this.ra()},g.w=function(){Y.H.w.call(this),k.clearTimeout(void 0),ua(this.f.a),this.f=null},t(Z,Y),Z.prototype.pa=function(){var t=new T,e=this.l;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.j&&(t.o=!0),t},Z.prototype.sa=function(t){return!t.i&&!t.a},Pe.prototype.createWebChannel=Pe.prototype.a,X.prototype.send=X.prototype.ab,X.prototype.open=X.prototype.$a,X.prototype.close=X.prototype.close,Ec.NO_ERROR=0,Ec.TIMEOUT=8,Ec.HTTP_ERROR=6,Fc.COMPLETE="complete",Gc.EventType=Hc,Hc.OPEN="a",Hc.CLOSE="b",Hc.ERROR="c",Hc.MESSAGE="d",A.prototype.listen=A.prototype.Ha,Z.prototype.getObject=Z.prototype.da,Z.prototype.releaseObject=Z.prototype.jb,T.prototype.listenOnce=T.prototype.Ia,T.prototype.getLastError=T.prototype.bb,T.prototype.getLastErrorCode=T.prototype.Fa,T.prototype.getStatus=T.prototype.W,T.prototype.getStatusText=T.prototype.Ga,T.prototype.getResponseJson=T.prototype.Za,T.prototype.getResponseText=T.prototype.V,T.prototype.getResponseText=T.prototype.V,T.prototype.send=T.prototype.fa,module.exports={createWebChannelTransport:Te,ErrorCode:Ec,EventType:Fc,WebChannel:Gc,XhrIoPool:Z}}).call(void 0!==global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}).call(exports,__webpack_require__(11))},22:function(t,e,n){"use strict";function r(t){o.forEach(function(e){e.logLevel=t})}Object.defineProperty(e,"__esModule",{value:!0});var i,o=[];!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(i||(i={}));var a=i.INFO,s=function(t,e){for(var n=[],r=2;r maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nfunction validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nfunction validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nfunction isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nfunction valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nfunction tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nfunction validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nfunction validateOptionNames(functionName, options, optionNames) {\n forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nfunction invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/misc.js\n/**\n * Copyright 2017 Google Inc.\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// tslint:disable-next-line:class-as-namespace\nvar misc_AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\n\nfunction primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using equals(). */\nfunction equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.equals(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using equals(). */\nfunction arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].equals(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nfunction immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nfunction immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/blob.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!platform_PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar blob_Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = platform_PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return platform_PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._equals = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nvar PublicBlob = makeConstructorPrivate(blob_Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/geo_point.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar geo_point_GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._equals = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\n\n\n//# sourceMappingURL=geo_point.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/database_info.js\n/**\n * Copyright 2017 Google Inc.\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\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\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 */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\n\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar database_info_DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.equals = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\n\n\n//# sourceMappingURL=database_info.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/path.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar path___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\nvar DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar path_Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.equals = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar path_ResourcePath = /** @class */ (function (_super) {\n path___extends(ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\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 ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\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 if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(path_Path));\n\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar path_FieldPath = /** @class */ (function (_super) {\n path___extends(FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_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 */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(path_Path));\n\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_key.js\n/**\n * Copyright 2017 Google Inc.\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\nvar document_key_DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.equals = function (other) {\n return (other !== null && path_ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return path_ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new path_ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(path_ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new path_ResourcePath([]));\n return DocumentKey;\n}());\n\n\n//# sourceMappingURL=document_key.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document.js\n/**\n * Copyright 2017 Google Inc.\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\nvar document_Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.equals = function (other) {\n return (other instanceof Document &&\n this.key.equals(other.key) &&\n this.version.equals(other.version) &&\n this.data.equals(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\n\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar document_NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.equals = function (other) {\n return (other && other.version.equals(this.version) && other.key.equals(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\n\n\n//# sourceMappingURL=document.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_map.js\n/**\n * Copyright 2017 Google Inc.\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 sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar sorted_map_SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : sorted_map_LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n // Returns the key of the item *before* the specified key, or null if key is\n // the first item.\n SortedMap.prototype.getPredecessorKey = function (key) {\n var node = this.root;\n var rightParent = null;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw fail('Attempted to find predecessor key for a nonexistent key.' +\n ' What gives?');\n };\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\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 SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\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 SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, true, resultGenerator);\n };\n return SortedMap;\n}()); // end SortedMap\n\n// An iterator over an LLRBNode.\nvar sorted_map_SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse, resultGenerator) {\n this.resultGenerator = resultGenerator || null;\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\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(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result;\n if (this.resultGenerator)\n result = this.resultGenerator(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n if (this.resultGenerator) {\n return this.resultGenerator(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nvar sorted_map_LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\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 LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\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 LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\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 LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new sorted_map_LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\n\nsorted_map_LLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/field_value.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar field_value___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\nvar TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder = TypeOrder || (TypeOrder = {}));\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar field_value_FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\n\nvar NullValue = /** @class */ (function (_super) {\n field_value___extends(NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function () {\n return null;\n };\n NullValue.prototype.equals = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(field_value_FieldValue));\n\nvar field_value_BooleanValue = /** @class */ (function (_super) {\n field_value___extends(BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function () {\n return this.internalValue;\n };\n BooleanValue.prototype.equals = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(field_value_FieldValue));\n\n/** Base class for IntegerValue and DoubleValue. */\nvar NumberValue = /** @class */ (function (_super) {\n field_value___extends(NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function () {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(field_value_FieldValue));\n\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar IntegerValue = /** @class */ (function (_super) {\n field_value___extends(IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.equals = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via equals().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(NumberValue));\n\nvar DoubleValue = /** @class */ (function (_super) {\n field_value___extends(DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.equals = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via equals().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue));\n\n// TODO(b/37267885): Add truncation support\nvar field_value_StringValue = /** @class */ (function (_super) {\n field_value___extends(StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function () {\n return this.internalValue;\n };\n StringValue.prototype.equals = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(field_value_FieldValue));\n\nvar TimestampValue = /** @class */ (function (_super) {\n field_value___extends(TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function () {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.equals = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.equals(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(field_value_FieldValue));\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they evaluate to null.\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\nvar ServerTimestampValue = /** @class */ (function (_super) {\n field_value___extends(ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function () {\n return null;\n };\n ServerTimestampValue.prototype.equals = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.equals(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(field_value_FieldValue));\n\nvar BlobValue = /** @class */ (function (_super) {\n field_value___extends(BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function () {\n return this.internalValue;\n };\n BlobValue.prototype.equals = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue._equals(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(field_value_FieldValue));\n\nvar field_value_RefValue = /** @class */ (function (_super) {\n field_value___extends(RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function () {\n return this.key;\n };\n RefValue.prototype.equals = function (other) {\n if (other instanceof RefValue) {\n return (this.key.equals(other.key) && this.databaseId.equals(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : document_key_DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(field_value_FieldValue));\n\nvar GeoPointValue = /** @class */ (function (_super) {\n field_value___extends(GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function () {\n return this.internalValue;\n };\n GeoPointValue.prototype.equals = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue._equals(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(field_value_FieldValue));\n\nvar field_value_ObjectValue = /** @class */ (function (_super) {\n field_value___extends(ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function () {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value();\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.equals = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.equals(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new sorted_map_SortedMap(primitiveComparator));\n return ObjectValue;\n}(field_value_FieldValue));\n\nvar field_value_ArrayValue = /** @class */ (function (_super) {\n field_value___extends(ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function () {\n return this.internalValue.map(function (v) { return v.value(); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.equals = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].equals(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(field_value_FieldValue));\n\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/types.js\n/**\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nvar isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction isNullOrUndefined(value) {\n return value === null || value === undefined;\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 */\nfunction isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nfunction safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/query.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar query_Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\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 if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new query_OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.equals(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof query_RelationFilter) ||\n !filter.isInequality() ||\n filter.field.equals(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\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.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.equals = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].equals(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].equals(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.equals(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.equals(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.equals(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return document_key_DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (document_key_DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.equals(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\n\nvar query_RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.equals = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\n\nvar query_RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof field_value_RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = document_key_DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case query_RelationOp.LESS_THAN:\n return comparison < 0;\n case query_RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case query_RelationOp.EQUAL:\n return comparison === 0;\n case query_RelationOp.GREATER_THAN:\n return comparison > 0;\n case query_RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== query_RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\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 (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.equals = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.equals(other.op) &&\n this.field.equals(other.field) &&\n this.value.equals(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\n\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.equals = function (other) {\n if (other instanceof NullFilter) {\n return this.field.equals(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\n\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.equals = function (other) {\n if (other instanceof NanFilter) {\n return this.field.equals(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\n\n/**\n * Creates a filter based on the provided arguments.\n */\nfunction fieldFilter(field, op, value) {\n if (value.equals(NullValue.INSTANCE)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.equals(DoubleValue.NAN)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new query_RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\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 */\nvar query_Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof field_value_RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = document_key_DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.equals = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.equals(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar query_OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? document_Document.compareByKey(d1, d2)\n : document_Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.equals = function (other) {\n return this.dir === other.dir && this.field.equals(other.field);\n };\n return OrderBy;\n}());\n\nvar KEY_ORDERING_ASC = new query_OrderBy(path_FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new query_OrderBy(path_FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/timestamp.js\n/**\n * Copyright 2017 Google Inc.\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\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar timestamp_Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\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 var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = parseInt(nanoStr, 10);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.equals = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\n\n\n//# sourceMappingURL=timestamp.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/snapshot_version.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar snapshot_version_SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new timestamp_Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.equals = function (other) {\n return this.timestamp.equals(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new timestamp_Timestamp(0, 0));\n return SnapshotVersion;\n}());\n\n\n//# sourceMappingURL=snapshot_version.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/query_data.js\n/**\n * Copyright 2017 Google Inc.\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\n/** An enumeration of the different purposes we have for queries. */\nvar QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose = QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar query_data_QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = snapshot_version_SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.equals = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.equals(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.equals(other.query));\n };\n return QueryData;\n}());\n\n\n//# sourceMappingURL=query_data.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar mutation___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\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 */\nvar mutation_FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.equals = function (other) {\n return arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\n\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.equals = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\n\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.equals = function (other) {\n return (this.field.equals(other.field) && this.transform.equals(other.transform));\n };\n return FieldTransform;\n}());\n\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\n\nvar MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType = MutationType || (MutationType = {}));\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 */\nvar mutation_Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof document_Document && maybeDoc.version.equals(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof document_Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof document_NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.equals = function (other) {\n return (equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\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 it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we 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 null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar mutation_Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.equals(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n return maybeDoc.version;\n }\n else {\n return snapshot_version_SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar mutation_SetMutation = /** @class */ (function (_super) {\n mutation___extends(SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\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 var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.equals = function (other) {\n return (other instanceof SetMutation &&\n this.key.equals(other.key) &&\n this.value.equals(other.value) &&\n this.precondition.equals(other.precondition));\n };\n return SetMutation;\n}(mutation_Mutation));\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 */\nvar mutation_PatchMutation = /** @class */ (function (_super) {\n mutation___extends(PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.equals = function (other) {\n return (other instanceof PatchMutation &&\n this.key.equals(other.key) &&\n this.fieldMask.equals(other.fieldMask) &&\n this.precondition.equals(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof document_Document) {\n data = maybeDoc.data;\n }\n else {\n data = field_value_ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(mutation_Mutation));\n\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar mutation_TransformMutation = /** @class */ (function (_super) {\n mutation___extends(TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = mutation_Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.equals = function (other) {\n return (other instanceof TransformMutation &&\n this.key.equals(other.key) &&\n arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.equals(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof document_Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.equals(this.key), 'Can only transform a document with the same key');\n return doc;\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 * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n transformResults.push(new ServerTimestampValue(localWriteTime));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(mutation_Mutation));\n\n/** A mutation that deletes the document at the given key. */\nvar mutation_DeleteMutation = /** @class */ (function (_super) {\n mutation___extends(DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\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 return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.equals(this.key), 'Can only apply mutation to document with same key');\n }\n return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.equals = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.equals(other.key) &&\n this.precondition.equals(other.precondition));\n };\n return DeleteMutation;\n}(mutation_Mutation));\n\n\n//# sourceMappingURL=mutation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/existence_filter.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.equals = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\n\n\n//# sourceMappingURL=existence_filter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/rpc_error.js\n/**\n * Copyright 2017 Google Inc.\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\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.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nfunction isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\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 */\nfunction mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\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 mapCodeFromRpcCode(code) {\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nfunction mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nfunction mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_set.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar sorted_set_SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new sorted_map_SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.equals = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\n\n\n//# sourceMappingURL=sorted_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/collections.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar EMPTY_MAYBE_DOCUMENT_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\nfunction documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new sorted_set_SortedSet(document_key_DocumentKey.comparator);\nfunction documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_event.js\n/**\n * Copyright 2017 Google Inc.\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\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 */\nvar remote_event_RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \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 documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: snapshot_version_SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\n\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nvar CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate = CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.equals = function (other) {\n return other !== null && this.docs.equals(other.docs);\n };\n return ResetMapping;\n}());\n\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.equals = function (other) {\n return (other !== null &&\n this.addedDocuments.equals(other.addedDocuments) &&\n this.removedDocuments.equals(other.removedDocuments));\n };\n return UpdateMapping;\n}());\n\n\n//# sourceMappingURL=remote_event.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/watch_change.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\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 */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \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 newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\n\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\n\nvar WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState = WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar watch_change_WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar watch_change_WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof watch_change_WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new remote_event_RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!contains(this.pendingTargetResponses, targetId) &&\n contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!contains(_this.pendingTargetResponses, targetId)) {\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 change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\n\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/serializer.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[query_RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[query_RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[query_RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[query_RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[query_RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return parseInt(value, 10);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar serializer_JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\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 (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return timestamp_Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new timestamp_Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return blob_Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return blob_Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return snapshot_version_SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = path_ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new document_key_DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return path_ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new path_ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new path_ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof field_value_BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof field_value_StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof field_value_ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof field_value_ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof field_value_RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return field_value_BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new field_value_StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new field_value_ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new GeoPointValue(new geo_point_GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new database_info_DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new document_key_DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new field_value_RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new document_Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = field_value_ObjectValue.EMPTY;\n forEach(map, function (key, value) {\n result = result.set(new path_FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new document_Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new document_NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result_type'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof document_Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof document_NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof watch_change_WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['change_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new watch_change_WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new document_Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : snapshot_version_SnapshotVersion.forDeletedDoc();\n var doc = new document_NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\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 // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof mutation_SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof mutation_DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof mutation_PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof mutation_TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : mutation_Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new mutation_PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new mutation_SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new mutation_DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new mutation_TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return mutation_Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return mutation_Precondition.exists(precondition.exists);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = path_FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return query_Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(path_ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toLimit(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = query.limit;\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new query_Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof query_RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toLimit = function (limit) {\n if (!isNullOrUndefined(limit)) {\n return limit;\n }\n return;\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new query_Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return query_RelationOp.EQUAL;\n case 'GREATER_THAN':\n return query_RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return query_RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return query_RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return query_RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return path_FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new query_OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof query_RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new query_RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return path_FieldPath.fromServerFormat(path); });\n return new mutation_FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\n\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n// EXTERNAL MODULE: ../webchannel-wrapper/dist/index.js\nvar dist = __webpack_require__(115);\nvar dist_default = /*#__PURE__*/__webpack_require__.n(dist);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/stream_bridge.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar stream_bridge_StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.wrappedOnOpen = null;\n this.wrappedOnClose = null;\n this.wrappedOnMessage = null;\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== null, 'Cannot call onOpen because no callback ' + 'was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== null, 'Cannot call onClose because no ' + 'callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== null, 'Cannot call onMessage because no ' + 'callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\n\n\n//# sourceMappingURL=stream_bridge.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar LOG_TAG = 'Connection';\nvar RPC_URL_VERSION = 'v1beta1';\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar webchannel_connection_WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new dist[\"XhrIoPool\"]();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n // This header is used to improve routing and project isolation by the\n // backend.\n headers['google-cloud-resource-prefix'] =\n \"projects/\" + this.databaseId.projectId + \"/\" +\n (\"databases/\" + this.databaseId.database);\n };\n WebChannelConnection.prototype.invoke = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(dist[\"EventType\"].COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case dist[\"ErrorCode\"].NO_ERROR:\n var json = xhr.getResponseJson();\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case dist[\"ErrorCode\"].TIMEOUT:\n log_error('RPC \"' + rpcName + '\" timed out, retrying.');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case dist[\"ErrorCode\"].HTTP_ERROR:\n var status_1 = xhr.getStatus();\n log_error('RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue, let's retry.\n log_error(LOG_TAG, 'RPC \"' + rpcName + '\" failed, retrying.');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var rpcService = WebChannelConnection.RPC_STREAM_SERVICE_MAPPING[rpcName];\n var rpcUrlName = WebChannelConnection.RPC_STREAM_NAME_MAPPING[rpcName];\n if (!rpcService || !rpcUrlName) {\n fail('Unknown RPC name: ' + rpcName);\n }\n var urlParts = [\n this.baseUrl,\n '/',\n rpcService,\n '/',\n rpcUrlName,\n '/channel'\n ];\n var webchannelTransport = Object(dist[\"createWebChannelTransport\"])();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n sendRawJson: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\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 var opened = false;\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 var closed = false;\n // tslint:disable-next-line:no-any\n var streamBridge = new stream_bridge_StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\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 var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(dist[\"WebChannel\"].EventType.OPEN, function () {\n if (!closed) {\n debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.MESSAGE, function (msg) {\n if (!closed) {\n // WebChannel delivers message events as array. If batching\n // is not enabled (it's off by default) each message will be\n // delivered alone, resulting in a single element array.\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\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 var error = msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n }\n else {\n debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\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 streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(rpcName);\n return url.join('');\n };\n /**\n * Mapping from RPC name to service providing the RPC.\n * For streaming RPCs only.\n */\n WebChannelConnection.RPC_STREAM_SERVICE_MAPPING = {\n Write: 'google.firestore.v1beta1.Firestore',\n Listen: 'google.firestore.v1beta1.Firestore'\n };\n /**\n * Mapping from RPC name to actual RPC name in URLs.\n * For streaming RPCs only.\n */\n WebChannelConnection.RPC_STREAM_NAME_MAPPING = {\n Write: 'Write',\n Listen: 'Listen'\n };\n return WebChannelConnection;\n}());\n\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_platform.js\n/**\n * Copyright 2017 Google Inc.\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\nvar browser_platform_BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new webchannel_connection_WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new serializer_JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\n\n\n//# sourceMappingURL=browser_platform.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_init.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nplatform_PlatformSupport.setPlatform(new browser_platform_BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_path.js\n/**\n * Copyright 2017 Google Inc.\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\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar field_path_FieldPath = /** @class */ (function () {\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 function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new path_FieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(path_FieldPath.keyField().canonicalString());\n return FieldPath;\n}());\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nfunction fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (field_path_FieldPath.bind.apply(field_path_FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/types.js\n/**\n * Copyright 2017 Google Inc.\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/** Describes the online state of the Firestore client */\nvar OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it was\n * previously in an unknown state and is trying to establish a connection.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * succesful message received from the backends.\n */\n OnlineState[OnlineState[\"Healthy\"] = 1] = \"Healthy\";\n /**\n * The client has tried to establish a connection but has failed.\n * This state is reached after either a connection attempt failed or a\n * healthy stream was closed for unexpected reasons.\n */\n OnlineState[OnlineState[\"Failed\"] = 2] = \"Failed\";\n})(OnlineState = OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view_snapshot.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType = ChangeType || (ChangeType = {}));\nvar SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState = SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar view_snapshot_DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\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('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\n\n\n//# sourceMappingURL=view_snapshot.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_set.js\n/**\n * Copyright 2017 Google Inc.\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\n\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 */\nvar document_set_DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new sorted_map_SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\n return this.sortedSet.isEmpty();\n };\n /**\n * Returns previous document or null if it's a first doc.\n *\n * @param key A key that MUST be present in the DocumentSet.\n */\n DocumentSet.prototype.prevDoc = function (key) {\n assert(this.has(key), 'Trying to get a previous document to non-existing key: ' + key);\n var doc = this.keyedMap.get(key);\n return this.sortedSet.getPredecessorKey(doc);\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 */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.equals = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.equals(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\n\n\n//# sourceMappingURL=document_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/obj_map.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar obj_map_ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.equals(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].equals(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].equals(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return isEmpty(this.inner);\n };\n return ObjectMap;\n}());\n\n\n//# sourceMappingURL=obj_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/event_manager.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar event_manager_EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.onOnlineStateChanged(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n var query = listener.query;\n var lastListen = false;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n var i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n else {\n return Promise.resolve();\n }\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.onOnlineStateChanged = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onOnlineStateChanged(onlineState);\n }\n });\n };\n return EventManager;\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 */\nvar event_manager_QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\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.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = {\n query: snap.query,\n docs: snap.docs,\n oldDocs: snap.oldDocs,\n docChanges: docChanges,\n fromCache: snap.fromCache,\n hasPendingWrites: snap.hasPendingWrites,\n syncStateChanged: snap.syncStateChanged\n };\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.onOnlineStateChanged = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Failed\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Failed;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Failed;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\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 (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\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 return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = {\n query: snap.query,\n docs: snap.docs,\n oldDocs: document_set_DocumentSet.emptySet(snap.docs),\n docChanges: QueryListener.getInitialViewChanges(snap),\n fromCache: snap.fromCache,\n hasPendingWrites: snap.hasPendingWrites,\n syncStateChanged: true\n };\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\n\n\n//# sourceMappingURL=event_manager.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/persistence_promise.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar persistence_promise_PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\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;\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = null;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_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(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\n\n\n//# sourceMappingURL=persistence_promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/eager_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar eager_garbage_collector_EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return persistence_promise_PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = persistence_promise_PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return persistence_promise_PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\n\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_view_changes.js\n/**\n * Copyright 2017 Google Inc.\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\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 */\nvar local_view_changes_LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\n\n\n//# sourceMappingURL=local_view_changes.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/reference_set.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\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 */\nvar reference_set_ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new sorted_set_SortedSet(reference_set_DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new reference_set_DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new reference_set_DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(firstRef !== null && key.equals(firstRef.key));\n };\n return ReferenceSet;\n}());\n\nvar reference_set_DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (document_key_DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n document_key_DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\n\n\n//# sourceMappingURL=reference_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/target_id_generator.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\n\n\n//# sourceMappingURL=target_id_generator.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\n\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\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 */\nvar view_View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\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 = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new document_set_DocumentSet(query.docComparator.bind(query));\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 * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new view_snapshot_DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\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 //\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 var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof document_Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.equals(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.equals(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\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 needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n var limboChanges = this.applyTargetChange(targetChange);\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n return {\n snapshot: {\n query: this.query,\n docs: docChanges.documentSet,\n oldDocs: oldDocs,\n docChanges: changes,\n fromCache: newSyncState === SyncState.Local,\n syncStateChanged: syncStateChanged,\n hasPendingWrites: !docChanges.mutatedKeys.isEmpty()\n },\n limboChanges: limboChanges\n };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\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 */\n View.prototype.applyTargetChange = function (targetChange) {\n var _this = this;\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n // Recompute the set of limbo docs.\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n if (this.current) {\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n }\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\n\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case 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 case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/sync_engine.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar sync_engine_LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \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 view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar sync_engine_SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new reference_set_ReferenceSet();\n this.limboCollector = new eager_garbage_collector_EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\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 targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new view_View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\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 */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\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 some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\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 *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new document_NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\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 var docMap = new sorted_map_SortedMap(document_key_DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new document_NoDocument(limboKey, snapshot_version_SnapshotVersion.forDeletedDoc()));\n var event_1 = new remote_event_RemoteEvent(snapshot_version_SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\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 this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\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 this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new sorted_map_SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.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 (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n debug(sync_engine_LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n debug(sync_engine_LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = query_Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new query_data_QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\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 return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = local_view_changes_LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\n\n\n//# sourceMappingURL=sync_engine.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation_batch.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar mutation_batch_MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.equals(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.equals(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.equals(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.equals(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.equals = function (other) {\n return (this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\n\n/** The result of applying a mutation batch to the backend. */\nvar mutation_batch_MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\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=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\n\n\n//# sourceMappingURL=mutation_batch.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/encoded_resource_path.js\n/**\n * Copyright 2017 Google Inc.\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\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\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 */\nfunction decode(path) {\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 var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return path_ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\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 var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new path_ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nfunction prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_schema.js\n/**\n * Copyright 2017 Google Inc.\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\nvar SCHEMA_VERSION = 1;\n/** Performs database creation and (in the future) upgrades between versions. */\nfunction createOrUpgradeDb(db, oldVersion) {\n assert(oldVersion === 0, 'Unexpected upgrade from version ' + oldVersion);\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n // TODO(mikelehen): Get rid of \"as any\" if/when TypeScript fixes their\n // types. https://github.com/Microsoft/TypeScript/issues/14322\n db.createObjectStore(\n // tslint:disable-next-line:no-any\n DbMutationBatch.store, { keyPath: DbMutationBatch.keyPath });\n var targetDocumentsStore = db.createObjectStore(\n // tslint:disable-next-line:no-any\n DbTargetDocument.store, { keyPath: DbTargetDocument.keyPath });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n // NOTE: keys for these stores are specified explicitly rather than using a\n // keyPath.\n db.createObjectStore(indexeddb_schema_DbDocumentMutation.store);\n db.createObjectStore(DbRemoteDocument.store);\n db.createObjectStore(DbOwner.store);\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar indexeddb_schema_DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\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 DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\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 */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\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 */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\n\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\n\n/**\n * The list of all IndexedDB stored used by the SDK. This is used when creating\n * transactions so that access across all stores is done atomically.\n */\nvar ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n indexeddb_schema_DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/simple_db.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar simple_db_LOG_TAG = 'SimpleDb';\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 */\nvar simple_db_SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(simple_db_LOG_TAG, 'Opening database:', name);\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\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.\n var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(simple_db_LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n // TODO(mikelehen): If/when we need to do an actual data\n // migration, we'll want to wrap db in a SimpleDb and have the\n // runUpgrade function return a PersistencePromise, since we'll\n // likely need to do async reads and writes. For now we're\n // cheating and just passing the raw IndexedDB in, since\n // createObjectStore(), etc. are synchronous.\n var db = event.target.result;\n runUpgrade(db, event.oldVersion);\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(simple_db_LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\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 var ua = window.navigator.userAgent;\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 if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = new simple_db_SimpleDbTransaction(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return persistence_promise_PersistencePromise.reject(error);\n })\n .toPromise();\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 return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\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 */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\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 */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar simple_db_SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(db, mode, objectStoresNames) {\n var _this = this;\n this.aborted = false;\n this.transaction = db.transaction(objectStoresNames, mode);\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(simple_db_LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore 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 */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new simple_db_SimpleDbStore(store);\n };\n return SimpleDbTransaction;\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 */\nvar simple_db_SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\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 * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(simple_db_LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(simple_db_LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(simple_db_LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof persistence_promise_PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return persistence_promise_PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar indexeddb_mutation_queue_IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\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 */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\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 assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isUnauthenticated() ? '' : user.uid;\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var encodedPath = encode(mutation.key.path);\n var indexKey = indexeddb_schema_DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, indexeddb_schema_DbDocumentMutation.PLACEHOLDER);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(batchId + 1));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId > batchId, 'Should have found mutation after ' + batchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\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 var path = decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.equals(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var encodedQueryPath = indexPrefix[1];\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\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 var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\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 if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = indexeddb_schema_DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return persistence_promise_PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(indexeddb_schema_DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, _, control) {\n var userID = key[0], keyPath = key[1], batchID = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\n\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, indexeddb_schema_DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\nvar indexeddb_query_cache_IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, snapshot_version_SnapshotVersion.MIN.toTimestamp());\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n if (metadata !== null) {\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.fromTimestamp(new timestamp_Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n }\n return persistence_promise_PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n var targetId = queryData.targetId;\n var addedQueryPromise = targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n if (targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = targetId;\n return addedQueryPromise.next(function () {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, _this.metadata);\n });\n }\n else {\n return addedQueryPromise;\n }\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId).next(function () {\n targetsStore(transaction).delete(queryData.targetId);\n });\n };\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\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 efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.equals(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var promises = [];\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction indexeddb_query_cache_getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\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 var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_serializer.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/** Serializer for values stored in the LocalStore. */\nvar local_serializer_LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = document_key_DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new timestamp_Timestamp(readTime.seconds, readTime.nanos);\n return new document_NoDocument(key, snapshot_version_SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = timestamp_Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new mutation_batch_MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new timestamp_Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = snapshot_version_SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new query_data_QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_persistence.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\nvar indexeddb_persistence_LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar indexeddb_persistence_IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new local_serializer_LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return simple_db_SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return indexeddb_mutation_queue_IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new indexeddb_query_cache_IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n debug(indexeddb_persistence_LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return simple_db_SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n debug(indexeddb_persistence_LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n debug(indexeddb_persistence_LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n debug(indexeddb_persistence_LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log_error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log_error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n debug(indexeddb_persistence_LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error(indexeddb_persistence_LOG_TAG, 'Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error(indexeddb_persistence_LOG_TAG, 'Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return misc_AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\n\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_documents_view.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\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 */\nvar local_documents_view_LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\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 */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new document_NoDocument(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (document_key_DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new document_key_DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof document_Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof document_Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof document_Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof document_NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\n\n\n//# sourceMappingURL=local_documents_view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n/**\n * Copyright 2017 Google Inc.\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\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 * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar remote_document_change_buffer_RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\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 * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return persistence_promise_PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\n\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_store.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\nvar local_store_LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar local_store_LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new reference_set_ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new local_documents_view_LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\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 LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new local_documents_view_LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return persistence_promise_PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = timestamp_Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge 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 */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\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 */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update 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 */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new remote_document_change_buffer_RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.addQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.equals(snapshot_version_SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n debug(local_store_LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\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 var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.equals(snapshot_version_SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return persistence_promise_PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\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 */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new query_data_QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\n\n\n//# sourceMappingURL=local_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\nvar memory_mutation_queue_MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\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.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new reference_set_DocReference(mutation.key, batchId));\n }\n return persistence_promise_PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return persistence_promise_PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n batchId = Math.max(batchId + 1, this.highestAcknowledgedBatchId);\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(batchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return persistence_promise_PersistencePromise.resolve(batch);\n }\n }\n return persistence_promise_PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new reference_set_DocReference(documentKey, 0);\n var end = new reference_set_DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.equals(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.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 var startPath = prefix;\n if (!document_key_DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new reference_set_DocReference(new document_key_DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\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 if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\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 var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new reference_set_DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(key.equals(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return persistence_promise_PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\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 */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return 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 */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\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 var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\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 */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\n\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_query_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar memory_query_cache_MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new obj_map_ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new reference_set_ReferenceSet();\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return persistence_promise_PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\n\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar memory_remote_document_cache_MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return persistence_promise_PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\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 var prefix = new document_key_DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return persistence_promise_PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\n\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_persistence.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar memory_persistence_LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar memory_persistence_MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new memory_remote_document_cache_MemoryRemoteDocumentCache();\n this.queryCache = new memory_query_cache_MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n // No durable state to read on startup.\n return Promise.resolve();\n };\n MemoryPersistence.prototype.shutdown = function () {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return Promise.resolve();\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new memory_mutation_queue_MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(memory_persistence_LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\n\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar no_op_garbage_collector_NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\n\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/promise.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\n\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nfunction sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/backoff.js\n/**\n * Copyright 2017 Google Inc.\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\nvar backoff_LOG_TAG = 'ExponentialBackoff';\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 */\nvar backoff_ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\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 initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \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 */\n maxDelayMs) {\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n 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 */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\n };\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts.\n */\n ExponentialBackoff.prototype.backoffAndWait = function () {\n var def = new Deferred();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n debug(backoff_LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n setTimeout(function () {\n def.resolve();\n }, delayWithJitterMs);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n return def.promise;\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\n\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/persistent_stream.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar persistent_stream___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\nvar persistent_stream_LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\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 *\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\n * onClose 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 */\nvar persistent_stream_PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connection, credentialsProvider, listener, \n // Used for faster retries in testing\n initialBackoffDelay) {\n this.queue = queue;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.stream = null;\n this.listener = null;\n this.backoff = new backoff_ExponentialBackoff(initialBackoffDelay ? initialBackoffDelay : BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\n this.listener = listener;\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 */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\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 ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function () {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.auth();\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 */\n PersistentStream.prototype.stop = function () {\n // Prevent any possible future restart of this stream\n this.state = PersistentStreamState.Stopped;\n // Clear the listener to avoid bleeding of events from the underlying\n // streams\n this.listener = null;\n // Clean up the underlying stream because we are no longer interested in\n // events\n if (this.stream !== null) {\n this.stream.close();\n this.stream = null;\n }\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 function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\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.startStream(token);\n }, function (error) {\n _this.queue.schedule(function () {\n if (_this.state !== PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return _this.handleStreamClose(rpcError);\n }\n else {\n return Promise.resolve();\n }\n });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfNotStopped = function (fn) {\n _this.queue.schedule(function () {\n // Only raise events if the listener has not changed\n if (_this.state !== PersistentStreamState.Stopped) {\n return fn();\n }\n else {\n return Promise.resolve();\n }\n });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n this.stream = this.startRpc(token);\n this.stream.onOpen(function () {\n dispatchIfNotStopped(function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfNotStopped(function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfNotStopped(function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndWait().then(function () {\n // Backoff does not run on the AsyncQueue, so we need to reschedule to\n // make sure the queue blocks\n _this.queue.schedule(function () {\n if (_this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for backoff to complete.\n return Promise.resolve();\n }\n _this.state = PersistentStreamState.Initial;\n _this.start();\n assert(_this.isStarted(), 'PersistentStream should have started');\n return Promise.resolve();\n });\n });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n debug(persistent_stream_LOG_TAG, \"close with error: \" + error);\n this.stream = null;\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 this.state = PersistentStreamState.Error;\n if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n debug(persistent_stream_LOG_TAG, 'Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n return this.listener.onClose(error);\n };\n return PersistentStream;\n}());\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar PersistentListenStream = /** @class */ (function (_super) {\n persistent_stream___extends(PersistentListenStream, _super);\n function PersistentListenStream(databaseInfo, queue, connection, credentials, serializer, listener, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, listener, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.stream.send(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.stream.send(request);\n };\n return PersistentListenStream;\n}(persistent_stream_PersistentStream));\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 */\nvar persistent_stream_PersistentWriteStream = /** @class */ (function (_super) {\n persistent_stream___extends(PersistentWriteStream, _super);\n function PersistentWriteStream(databaseInfo, queue, connection, credentials, serializer, listener, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, listener, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function () {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this);\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\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.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\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 */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\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 var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.stream.send(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.stream.send(request);\n };\n return PersistentWriteStream;\n}(persistent_stream_PersistentStream));\n\n\n//# sourceMappingURL=persistent_stream.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/datastore.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar datastore_Datastore = /** @class */ (function () {\n function Datastore(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n this.databaseInfo = databaseInfo;\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n this.initialBackoffDelay = initialBackoffDelay;\n }\n Datastore.prototype.newPersistentWriteStream = function (listener) {\n return new persistent_stream_PersistentWriteStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, listener, this.initialBackoffDelay);\n };\n Datastore.prototype.newPersistentWatchStream = function (listener) {\n return new PersistentListenStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, listener, this.initialBackoffDelay);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeRPC('batchGet', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invoke(rpcName, request, token);\n });\n };\n return Datastore;\n}());\n\n\n//# sourceMappingURL=datastore.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/transaction.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar transaction_Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof document_NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = snapshot_version_SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.equals(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\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 */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return mutation_Precondition.updateTime(version);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.equals(snapshot_version_SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return mutation_Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return mutation_Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new mutation_DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\n\n\n//# sourceMappingURL=transaction.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_store.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar remote_store_LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n// The RemoteStore notifies an onlineStateHandler with OnlineState.Failed if we\n// fail to connect to the backend. This subsequently triggers get() requests to\n// fail or use cached data, etc. Unfortunately, our connections have\n// historically been subject to various transient failures. So we wait for\n// multiple failures before notifying the onlineStateHandler.\nvar ONLINE_ATTEMPTS_BEFORE_FAILURE = 2;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar remote_store_RemoteStore = /** @class */ (function () {\n function RemoteStore(databaseInfo, asyncQueue, \n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, onlineStateHandler) {\n this.databaseInfo = databaseInfo;\n this.asyncQueue = asyncQueue;\n this.localStore = localStore;\n this.datastore = datastore;\n this.onlineStateHandler = onlineStateHandler;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\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.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n /**\n * The online state of the watch stream. The state is set to healthy if and\n * only if there are messages received by the backend.\n */\n this.watchStreamOnlineState = OnlineState.Unknown;\n /** A count of consecutive failures to open the stream. */\n this.watchStreamFailures = 0;\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n RemoteStore.prototype.setOnlineStateToHealthy = function () {\n this.updateAndBroadcastOnlineState(OnlineState.Healthy);\n };\n RemoteStore.prototype.setOnlineStateToUnknown = function () {\n // The state is set to unknown when a healthy stream is closed (e.g. due to\n // a token timeout) or when we have no active listens and therefore there's\n // no need to start the stream. Assuming there is (possibly in the future)\n // an active listen, then we will eventually move to state Online or Failed,\n // but we always want to make at least ONLINE_ATTEMPTS_BEFORE_FAILURE\n // attempts before failing, so we reset the count here.\n this.watchStreamFailures = 0;\n this.updateAndBroadcastOnlineState(OnlineState.Unknown);\n };\n RemoteStore.prototype.updateOnlineStateAfterFailure = function () {\n // The first failure after we are successfully connected moves us to the\n // 'Unknown' state. We then may make multiple attempts (based on\n // ONLINE_ATTEMPTS_BEFORE_FAILURE) before we actually report failure.\n if (this.watchStreamOnlineState === OnlineState.Healthy) {\n this.setOnlineStateToUnknown();\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= ONLINE_ATTEMPTS_BEFORE_FAILURE) {\n this.updateAndBroadcastOnlineState(OnlineState.Failed);\n }\n }\n };\n RemoteStore.prototype.updateAndBroadcastOnlineState = function (onlineState) {\n var didChange = this.watchStreamOnlineState !== onlineState;\n this.watchStreamOnlineState = onlineState;\n if (didChange) {\n this.onlineStateHandler(onlineState);\n }\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) == (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Only to be called as the counterpart to disableNetwork(). */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n assert(this.watchStream == null, 'enableNetwork() called with non-null watchStream.');\n assert(this.writeStream == null, 'enableNetwork() called with non-null writeStream.');\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n this.writeStream = this.datastore.newPersistentWriteStream({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n _this.updateAndBroadcastOnlineState(OnlineState.Unknown);\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /** Temporarily disables the network. The network can be re-enabled using enableNetwork(). */\n RemoteStore.prototype.disableNetwork = function () {\n this.updateAndBroadcastOnlineState(OnlineState.Failed);\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n return Promise.resolve();\n };\n RemoteStore.prototype.shutdown = function () {\n debug(remote_store_LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetwork();\n return Promise.resolve(undefined);\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n var queryData = this.listenTargets[targetId];\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\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 */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\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 */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start();\n };\n /**\n * Returns whether the watch stream should be started because there are\n * active targets trying to be listened too\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n var _this = this;\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.updateOnlineStateAfterFailure();\n this.startWatchStream();\n }\n else {\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 this.setOnlineStateToUnknown();\n }\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n // Mark the connection as healthy because we got a message from the server\n this.setOnlineStateToHealthy();\n if (watchChange instanceof watch_change_WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.equals(snapshot_version_SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n var changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return this.handleWatchChangeBatch(snapshotVersion, changes);\n }\n else {\n return Promise.resolve();\n }\n };\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 RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new watch_change_WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new document_key_DocumentKey(query.path);\n var deletedDoc = new document_NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new query_data_QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new query_data_QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () {\n if (contains(_this.listenTargets, targetId)) {\n delete _this.listenTargets[targetId];\n return _this.syncEngine.rejectListen(targetId, error);\n }\n else {\n // A watched target might have been removed already.\n return Promise.resolve();\n }\n });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n *\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n var _this = this;\n if (!this.canWriteMutations()) {\n return Promise.resolve();\n }\n else {\n return this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n return Promise.resolve();\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n });\n }\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start();\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n this.writeStream.writeHandshake();\n return Promise.resolve();\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = mutation_batch_MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n var _this = this;\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // Ignore close if there are no pending writes.\n if (this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n // A promise that is resolved after we processed the error\n var errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n });\n }\n else {\n // No pending writes, nothing to do\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n debug(remote_store_LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return this.localStore.setLastStreamToken(emptyByteString());\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n var _this = this;\n if (isPermanentError(error.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 var batch = this.pendingWrites.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 this.writeStream.inhibitBackoff();\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n });\n }\n else {\n // Transient error, just let the retry logic kick in.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.createTransaction = function () {\n return new transaction_Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n debug(remote_store_LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetwork();\n return this.enableNetwork();\n };\n return RemoteStore;\n}());\n\n\n//# sourceMappingURL=remote_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/firestore_client.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\nvar firestore_client_LOG_TAG = 'FirestoreClient';\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 */\nvar firestore_client_FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \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 asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.schedule(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.schedule(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new no_op_garbage_collector_NoOpGarbageCollector();\n var storagePrefix = indexeddb_persistence_IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new serializer_JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new indexeddb_persistence_IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new eager_garbage_collector_EagerGarbageCollector();\n this.persistence = new memory_persistence_MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new local_store_LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new datastore_Datastore(_this.databaseInfo, _this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.eventMgr.onOnlineStateChanged(onlineState);\n };\n _this.remoteStore = new remote_store_RemoteStore(_this.databaseInfo, _this.asyncQueue, _this.localStore, datastore, onlineStateChangedHandler);\n _this.syncEngine = new sync_engine_SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new event_manager_EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(firestore_client_LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .schedule(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new event_manager_QueryListener(query, observer, options);\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.schedule(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .schedule(function () {\n return Promise.resolve();\n })\n .then(function () {\n return _this.syncEngine.runTransaction(updateFunction);\n });\n };\n return FirestoreClient;\n}());\n\n\n//# sourceMappingURL=firestore_client.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_observer.js\n/**\n * Copyright 2017 Google Inc.\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 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 */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\n\n\n//# sourceMappingURL=async_observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar async_queue_AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // The number of ops that are queued to be run in the future (i.e. they had a\n // delay that has not yet elapsed).\n this.delayedOpCount = 0;\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n *\n * Can optionally specify a delay to wait before queuing the operation.\n */\n AsyncQueue.prototype.schedule = function (op, delay) {\n var _this = this;\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + this.failure.message);\n }\n if ((delay || 0) > 0) {\n this.delayedOpCount++;\n var deferred_1 = new Deferred();\n setTimeout(function () {\n _this.scheduleInternal(function () {\n return op().then(function (result) {\n deferred_1.resolve(result);\n });\n });\n _this.delayedOpCount--; // decrement once it's actually queued.\n }, delay);\n return deferred_1.promise;\n }\n else {\n return this.scheduleInternal(op);\n }\n };\n AsyncQueue.prototype.scheduleInternal = function (op) {\n var _this = this;\n this.tail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n log_error('INTERNAL UNHANDLED ERROR: ', error.stack || error.message);\n throw error;\n })\n .then(function () {\n _this.operationInProgress = false;\n });\n });\n return this.tail;\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n AsyncQueue.prototype.drain = function () {\n // TODO(mikelehen): This should perhaps also drain items that are queued to\n // run in the future (perhaps by artificially running them early), but since\n // no tests need that yet, I didn't bother for now.\n assert(this.delayedOpCount === 0, \"draining doesn't handle delayed ops.\");\n return this.schedule(function () { return Promise.resolve(undefined); });\n };\n return AsyncQueue;\n}());\n\n\n//# sourceMappingURL=async_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/auth/user.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isUnauthenticated = function () {\n return this.uid == null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isUnauthenticated()) {\n return 'anonymous-user';\n }\n else {\n return 'uid:' + this.uid;\n }\n };\n User.prototype.equals = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\n\n\n//# sourceMappingURL=user.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/credentials.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\n\n/** A CredentialsProvider that always yields an empty token. */\nvar credentials_EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\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.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\n\nvar credentials_FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.equals(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\n}());\n\n// Wrap a google-auth-library client as a CredentialsProvider.\n// NOTE: grpc-connection can natively accept a google-auth-library\n// client via createFromGoogleCredential(), but we opt to plumb the tokens\n// through our CredentialsProvider interface, at least for now.\nvar credentials_GoogleCredentialsProvider = /** @class */ (function () {\n function GoogleCredentialsProvider(authClient) {\n this.authClient = authClient;\n }\n GoogleCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n // TODO(b/32935141): ideally this would be declared as an extern\n _this.authClient['getAccessToken'](function (error, tokenLiteral) {\n if (error) {\n reject(error);\n }\n else {\n resolve(new OAuthToken(tokenLiteral, User.GOOGLE_CREDENTIALS));\n }\n });\n });\n };\n // NOTE: A google-auth-library client represents an immutable \"user\", so\n // once we fire the initial event, it'll never change.\n GoogleCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.GOOGLE_CREDENTIALS);\n };\n GoogleCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return GoogleCredentialsProvider;\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 * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar credentials_FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\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 */\nvar credentials_FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new credentials_FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nfunction makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new credentials_EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'google-auth':\n return new credentials_GoogleCredentialsProvider(credentials.client);\n case 'gapi':\n return new credentials_FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/observer.js\n/**\n * Copyright 2017 Google Inc.\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 isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_value.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar api_field_value___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n return FieldValueImpl;\n}());\n\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\n api_field_value___extends(DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\n\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n api_field_value___extends(ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/user_data_converter.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar user_data_converter_ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new mutation_PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new mutation_SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar user_data_converter_ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new mutation_PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar user_data_converter_ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * 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 function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n ParseContext.prototype.isWrite = function () {\n return (this.dataSource === UserDataSource.Set ||\n this.dataSource === UserDataSource.Update);\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar user_data_converter_UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call.*/\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.Set, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new user_data_converter_ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.MergeSet, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new mutation_FieldMask(context.fieldMask);\n return new user_data_converter_ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.QueryValue, methodName, path_FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\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 * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new field_value_ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new sorted_map_SortedMap(primitiveComparator);\n forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new field_value_ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (isSafeInteger(value)) {\n return new IntegerValue(value);\n }\n else {\n return new DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return field_value_BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new field_value_StringValue(value);\n }\n else if (value instanceof Date) {\n return new TimestampValue(timestamp_Timestamp.fromDate(value));\n }\n else if (value instanceof geo_point_GeoPoint) {\n return new GeoPointValue(value);\n }\n else if (value instanceof blob_Blob) {\n return new BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new field_value_RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource == UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\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 */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof geo_point_GeoPoint) &&\n !(input instanceof blob_Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nfunction fieldPathFromArgument(methodName, path) {\n if (path instanceof field_path_FieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\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 split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/database.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar database___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar database_FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.equals = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar database_Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n this.INTERNAL = {\n delete: function () {\n if (_this._firestoreClient) {\n return _this._firestoreClient.shutdown();\n }\n else {\n return Promise.resolve();\n }\n },\n // Exposed via INTERNAL for use in tests.\n disableNetwork: function () { return _this._firestoreClient.disableNetwork(); },\n enableNetwork: function () { return _this._firestoreClient.enableNetwork(); }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new credentials_FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new database_info_DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new credentials_EmptyCredentialsProvider();\n }\n config.settings = new database_FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new database_FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.equals(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof database_DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.equals(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new user_data_converter_UserDataConverter(preConverter);\n this._firestoreClient = new firestore_client_FirestoreClient(platform_PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, new async_queue_AsyncQueue());\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (contains(options, 'firestoreId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new database_info_DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new database_CollectionReference(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return database_DocumentReference.forPath(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new database_Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new database_WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n setLogLevel(LogLevel.DEBUG);\n break;\n case 'error':\n setLogLevel(LogLevel.ERROR);\n break;\n case 'silent':\n setLogLevel(LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\n\n/**\n * A reference to a transaction.\n */\nvar database_Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof document_NoDocument) {\n return new database_DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new database_DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\n\nvar database_WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new mutation_DeleteMutation(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n else {\n return Promise.resolve();\n }\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar database_DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new document_key_DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new database_CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = path_ResourcePath.fromString(pathString);\n return new database_CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.equals(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new mutation_DeleteMutation(this._key, mutation_Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new database_DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(query_Query.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.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 reject(new FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\n\nvar database_DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function () {\n validateExactNumberOfArgs('DocumentSnapshot.data', arguments, 0);\n if (!this._document) {\n throw new FirestoreError(Code.NOT_FOUND, \"This document doesn't exist. Check doc.exists to make sure \" +\n 'the document exists before calling doc.data().');\n }\n return this.convertObject(this._document.data);\n };\n DocumentSnapshot.prototype.get = function (fieldPath) {\n validateExactNumberOfArgs('DocumentSnapshot.get', arguments, 1);\n if (!this._document) {\n throw new FirestoreError(Code.NOT_FOUND, \"This document doesn't exist. Check doc.exists to make sure \" +\n 'the document exists before calling doc.get().');\n }\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n return value === undefined ? undefined : this.convertValue(value);\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new database_DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return {\n hasPendingWrites: this._document !== null && this._document.hasLocalMutations,\n fromCache: this._fromCache\n };\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.convertObject = function (data) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value) {\n if (value instanceof field_value_ObjectValue) {\n return this.convertObject(value);\n }\n else if (value instanceof field_value_ArrayValue) {\n return this.convertArray(value);\n }\n else if (value instanceof field_value_RefValue) {\n var key = value.value();\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.equals(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log_error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId\n .database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new database_DocumentReference(key, this._firestore);\n }\n else {\n return value.value();\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value);\n });\n };\n return DocumentSnapshot;\n}());\n\nvar database_Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new path_ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new field_value_RefValue(this.firestore._databaseId, new document_key_DocumentKey(path));\n }\n else if (value instanceof database_DocumentReference) {\n var ref = value;\n fieldValue = new field_value_RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, query_RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new query_OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.equals(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof database_DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\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.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\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 (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new field_value_RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new query_Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new document_key_DocumentKey(this._query.path.child(rawValue));\n components.push(new field_value_RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new query_Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new database_QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.equals(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.equals(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\n\nvar database_QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = {\n fromCache: _snapshot.fromCache,\n hasPendingWrites: _snapshot.hasPendingWrites\n };\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new database_Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new database_DocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\n\nvar database_CollectionReference = /** @class */ (function (_super) {\n database___extends(CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, query_Query.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new database_DocumentReference(new document_key_DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = misc_AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = path_ResourcePath.fromString(pathString);\n return database_DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(database_Query));\n\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof database_DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nfunction changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_DocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_DocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nvar PublicFirestore = makeConstructorPrivate(database_Firestore, 'Use firebase.firestore() instead.');\nvar PublicTransaction = makeConstructorPrivate(database_Transaction, 'Use firebase.firestore().runTransaction() instead.');\nvar PublicWriteBatch = makeConstructorPrivate(database_WriteBatch, 'Use firebase.firestore().batch() instead.');\nvar PublicDocumentReference = makeConstructorPrivate(database_DocumentReference, 'Use firebase.firestore().doc() instead.');\nvar PublicDocumentSnapshot = makeConstructorPrivate(database_DocumentSnapshot);\nvar PublicQuery = makeConstructorPrivate(database_Query);\nvar PublicQuerySnapshot = makeConstructorPrivate(database_QuerySnapshot);\nvar PublicCollectionReference = makeConstructorPrivate(database_CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform/config.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: geo_point_GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: field_path_FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: database_Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nfunction configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new database_Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nfunction configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = database_Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerFirestore\"] = registerFirestore;\n/**\n * Copyright 2017 Google Inc.\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\n\nfunction registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n\n/***/ 115:\n/***/ (function(module, exports, __webpack_require__) {\n\n(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function p(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var q=\"closure_uid_\"+(1E9*Math.random()>>>0),ea=0;function fa(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ha(a,b,c){if(!a)throw Error();if(2b?1:0};function na(a,b){b.unshift(a);ja.call(this,ka.apply(null,b));b.shift()}u(na,ja);na.prototype.name=\"AssertionError\";function oa(a,b){throw new na(\"Failure\"+(a?\": \"+a:\"\"),Array.prototype.slice.call(arguments,1));};function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this);this.i=this.i;this.v=this.v}var qa=0,ra={};w.prototype.i=!1;w.prototype.Y=function(){if(!this.i&&(this.i=!0,this.w(),0!=qa)){var a=this[q]||(this[q]=++ea);delete ra[a]}};w.prototype.w=function(){if(this.v)for(;this.v.length;)this.v.shift()()};var sa=Array.prototype.indexOf?function(a,b,c){return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(l(a))return l(b)&&1==b.length?a.indexOf(b,c):-1;for(;cb?null:l(a)?a.charAt(b):a[b]}function wa(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function xa(a){return Array.prototype.concat.apply([],arguments)}function ya(a){var b=a.length;if(0parseFloat(Qa)){Pa=String(Ta);break a}}Pa=Qa}var Ja={};\nfunction Ua(a){return Ia(a,function(){for(var b=0,c=la(String(Pa)).split(\".\"),d=la(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var cb=\"closure_listenable_\"+(1E6*Math.random()|0);function db(a){return!(!a||!a[cb])}var eb=0;function fb(a,b,c,d,e){this.listener=a;this.a=null;this.src=b;this.type=c;this.capture=!!d;this.da=e;this.key=++eb;this.X=this.ba=!1}function gb(a){a.X=!0;a.listener=null;a.a=null;a.src=null;a.da=null};function hb(a){this.src=a;this.a={};this.b=0}hb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=ib(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=yb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function qb(a){if(da(a))return a;a[Ab]||(a[Ab]=function(b){return a.handleEvent(b)});return a[Ab]};function B(){w.call(this);this.c=new hb(this);this.P=this;this.J=null}u(B,w);B.prototype[cb]=!0;g=B.prototype;g.addEventListener=function(a,b,c,d){ob(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){wb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.J;if(c)for(b=[];c;c=c.J)b.push(c);c=this.P;var d=a.type||a;if(l(a))a=new A(a,c);else if(a instanceof A)a.target=a.target||c;else{var e=a;a=new A(d,c);Ga(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Bb(h,d,!0,a)&&e}h=a.a=c;e=Bb(h,d,!0,a)&&e;e=Bb(h,d,!1,a)&&e;if(b)for(f=0;f=lc(this).value)for(da(b)&&(b=b()),a=new dc(a,String(b),this.f),c&&(a.a=c),c=\"log:\"+a.b,(a=k.console)&&a.timeStamp&&a.timeStamp(c),(a=k.msWriteProfilerMark)&&a(c),c=this;c;)c=c.a};function F(a,b){a.log(gc,b,void 0)}function G(a,b){a.log(hc,b,void 0)}var mc={},nc=null;\nfunction oc(a){nc||(nc=new fc(\"\"),mc[\"\"]=nc,nc.c=jc);var b;if(!(b=mc[a])){b=new fc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=oc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;mc[a]=b}return b};function pc(a,b){a&&a.log(ic,b,void 0)}function H(a,b){a&&a.log(kc,b,void 0)};function qc(){this.a=oc(\"goog.labs.net.webChannel.WebChannelDebug\")}function rc(a,b,c,d){if(c)try{var e=JSON.parse(c);if(e)for(var f=0;fh.length)){var m=h[1];if(n(m)&&!(1>m.length)){var v=m[0];if(\"noop\"!=v&&\"stop\"!=v&&\"close\"!=v)for(var Sa=1;Sab||3==b&&!Ka&&!this.a.U())){this.s||4!=b||7==c||uc();Rc(this);var d=this.a.V();this.v=d;var e=this.a.U();e||I(this.b,\"No response text for uri \"+this.g+\" status \"+d);this.c=200==d;I(this.b,\"XMLHTTP RESP (\"+this.f+\") [ attempt \"+this.S+\"]: \"+this.j+\"\\n\"+this.g+\"\\n\"+b+\" \"+d);if(this.c)this.J?(Sc(this,b,e),Ka&&this.c&&3==b&&(this.M.$(this.F,\"tick\",this.fb),this.F.start())):(rc(this.b,this.f,e,null),Tc(this,e)),4==b&&Uc(this),this.c&&\n!this.s&&(4==b?this.m.wa(this):(this.c=!1,Pc(this)));else{if(400==d&&0b.length)return Kc;b=b.substr(d,c);a.C=d+c;return b}g.cancel=function(){this.s=!0;Uc(this)};function Pc(a){a.T=t()+a.P;Xc(a,a.P)}function Xc(a,b){if(null!=a.o)throw Error(\"WatchDog timer not null\");a.o=xc(r(a.eb,a),b)}function Rc(a){a.o&&(k.clearTimeout(a.o),a.o=null)}\ng.eb=function(){this.o=null;var a=t();if(0<=a-this.T)this.c&&(a=this.b.a)&&F(a,\"Received watchdog timeout even though request loaded successfully\"),I(this.b,\"TIMEOUT: \"+this.g),2!=this.I&&(uc(),K()),Uc(this),this.i=2,Vc(this);else{var b=this.b.a;b&&G(b,\"WatchDog timer called too early\");Xc(this,this.T-a)}};function Vc(a){a.m.Ka()||a.s||a.m.wa(a)}function Uc(a){Rc(a);var b=a.G;b&&\"function\"==typeof b.Y&&b.Y();a.G=null;Yb(a.F);cc(a.M);a.a&&(b=a.a,a.a=null,b.abort(),b.Y())}\nfunction Tc(a,b){try{a.m.Na(a,b),uc()}catch(c){sc(a.b,c,\"Error in httprequest callback\")}};function Yc(a){if(a.A&&\"function\"==typeof a.A)return a.A();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&$c(a),!0):!1}function $c(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function hd(a,b,c){b instanceof kd?(a.c=b,qd(a.c,a.h)):(c||(b=ld(b,rd)),a.c=new kd(b,0,a.h))}\nfunction R(a,b,c){a.c.set(b,c)}function Qc(a,b,c){n(c)||(c=[String(c)]);sd(a.c,b,c)}function Mc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36));return a}function td(a){return a instanceof Q?M(a):new Q(a,void 0)}function ud(a,b,c,d){var e=new Q(null,void 0);a&&ed(e,a);b&&fd(e,b);c&&gd(e,c);d&&(e.a=d);return e}function jd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction ld(a,b,c){return l(a)?(a=encodeURI(a).replace(b,vd),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function vd(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var md=/[#\\/\\?@]/g,od=/[#\\?:]/g,nd=/[#\\?]/g,rd=/[#\\?@]/g,pd=/#/g;function kd(a,b,c){this.b=this.a=null;this.c=a||null;this.f=!!c}function S(a){a.a||(a.a=new O,a.b=0,a.c&&dd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=kd.prototype;g.u=function(){S(this);return this.b};\ng.add=function(a,b){S(this);this.c=null;a=wd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function xd(a,b){S(a);b=wd(a,b);P(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,bd(a.a,b))}function yd(a,b){S(a);b=wd(a,b);return P(a.a.b,b)}g.forEach=function(a,b){S(this);this.a.forEach(function(c,d){ta(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.O=function(){S(this);for(var a=this.a.A(),b=this.a.O(),c=[],d=0;d=a.c:!1}function Td(a,b){return a.b?a.b==b:a.a?a.a.contains(b):!1}function Rd(a,b){a.a?a.a.add(b):a.b=b}\nOd.prototype.cancel=function(){this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ta(this.a.A(),function(a){a.cancel()}),ad(this.a.a))};function Ud(a,b){this.a=a;this.b=b};function Vd(a,b){this.a=a;this.b=b}Vd.prototype.stringify=function(a){return k.JSON.stringify(a,this.a)};Vd.prototype.parse=function(a){return k.JSON.parse(a,this.b)};function Wd(){this.a=new Vd}function Xd(a,b,c){var d=c||\"\";try{Zc(a,function(a,c){var e=a;p(a)&&(e=Eb(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function Yd(a,b){var c=new qc;I(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ia(Zd,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ia(Zd,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ia(Zd,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ia(Zd,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function Zd(a,b,c,d,e){try{I(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){sc(a,f)}};function U(a){B.call(this);this.headers=new O;this.G=a||null;this.f=!1;this.F=this.a=null;this.M=this.s=\"\";this.j=0;this.g=\"\";this.h=this.I=this.o=this.H=!1;this.l=0;this.B=null;this.N=$d;this.C=this.m=!1}u(U,B);var $d=\"\";U.prototype.b=oc(\"goog.net.XhrIo\");var ae=/^https?$/i,be=[\"POST\",\"PUT\"];g=U.prototype;\ng.ta=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.s+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.s=a;this.g=\"\";this.j=0;this.M=b;this.H=!1;this.f=!0;this.a=this.G?Fc(this.G):Fc(Dc);this.F=this.G?Bc(this.G):Bc(Dc);this.a.onreadystatechange=r(this.Ma,this);try{H(this.b,V(this,\"Opening Xhr\")),this.I=!0,this.a.open(b,String(a),!0),this.I=!1}catch(f){H(this.b,V(this,\"Error opening Xhr: \"+f.message));ce(this,f);return}a=c||\"\";var e=new O(this.headers);\nd&&Zc(d,function(a,b){e.set(b,a)});d=ua(e.O());c=k.FormData&&a instanceof k.FormData;!(0<=sa(be,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.N&&(this.a.responseType=this.N);\"withCredentials\"in this.a&&this.a.withCredentials!==this.m&&(this.a.withCredentials=this.m);try{de(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}R(a,b,c);return a};function ke(a,b,c){this.za=b||0;this.Ba=0;this.h=[];this.l=[];this.a=new qc;this.J=c||new Md;this.ia=this.ya=this.H=this.ja=this.b=this.N=this.j=this.ha=this.f=this.P=this.i=null;this.Va=this.I=0;this.ka=this.C=this.s=this.m=this.o=this.c=null;this.v=this.Aa=this.S=-1;this.ga=this.B=this.G=0;this.T=a&&a.supportsCrossDomainXhr||!1;this.M=\"\";this.g=new Od(a&&a.concurrentRequestLimit);this.la=new Wd;this.F=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;this.Ua=a&&a.fastHandshake||!1}\ng=ke.prototype;g.oa=8;g.D=1;function le(a){I(a.a,\"disconnect()\");me(a);if(3==a.D){var b=a.I++,c=M(a.H);R(c,\"SID\",a.M);R(c,\"RID\",b);R(c,\"TYPE\",\"terminate\");ne(a,c);b=new L(a,a.a,0,b,void 0);b.I=2;b.l=Mc(M(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.l.toString(),\"\"));c||((new Image).src=b.l);b.H=t();Pc(b)}oe(a)}\nfunction me(a){a.C&&(a.C.abort(),a.C=null);a.b&&(a.b.cancel(),a.b=null);a.m&&(k.clearTimeout(a.m),a.m=null);pe(a);a.g.cancel();a.o&&(k.clearTimeout(a.o),a.o=null)}function qe(a,b){if(1E3==a.h.length){var c=\"Already have 1000 queued maps upon queueing \"+Eb(b),d=a.a.a;d&&F(d,c)}a.h.push(new Ud(a.Va++,b));3==a.D&&re(a)}g.Ka=function(){return 0==this.D};function re(a){Sd(a.g)||a.o||(a.o=xc(r(a.Pa,a),0),a.G=0)}\ng.Pa=function(a){this.o=null;I(this.a,\"startForwardChannel_\");if(1==this.D)if(a)(a=this.a.a)&&F(a,\"Not supposed to retry the open\");else{I(this.a,\"open_()\");this.I=Math.floor(1E5*Math.random());a=this.I++;var b=new L(this,this.a,0,a,void 0),c=this.i;this.P&&(c?(c=Ea(c),Ga(c,this.P)):c=this.P);null===this.f&&(b.h=c);var d=se(this),e=M(this.H);R(e,\"RID\",a);0b&&this.ka&&0==this.B&&!this.s&&(this.s=xc(r(this.ab,this),6E3)));else I(this.a,\"Bad POST response data returned\"),W(this,11)}else if(this.b==a&&pe(this),!/^[\\s\\xa0]*$/.test(b))for(b=c=this.la.a.parse(b),c=0;cthis.c)throw Error(Je);this.a=new Ge;this.b=new T;this.g=null;this.aa()}u(Ie,w);var Je=\"[goog.structs.Pool] Min can not be greater than max\";g=Ie.prototype;g.ca=function(){var a=t();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.u()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}Me.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)wa(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.ma=function(a){Y.L.ma.call(this,a);this.ua()};g.aa=function(){Y.L.aa.call(this);this.ua()};g.w=function(){Y.L.w.call(this);k.clearTimeout(void 0);wa(this.f.a);this.f=null};function Z(a,b,c,d){this.l=a;this.j=!!d;Y.call(this,b,c)}u(Z,Y);Z.prototype.qa=function(){var a=new U,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.m=!0);return a};Z.prototype.va=function(a){return!a.i&&!a.a};Be.prototype.createWebChannel=Be.prototype.a;X.prototype.send=X.prototype.l;X.prototype.open=X.prototype.j;X.prototype.close=X.prototype.close;yc.NO_ERROR=0;yc.TIMEOUT=8;yc.HTTP_ERROR=6;zc.COMPLETE=\"complete\";Dd.EventType=Ed;Ed.OPEN=\"a\";Ed.CLOSE=\"b\";Ed.ERROR=\"c\";Ed.MESSAGE=\"d\";B.prototype.listen=B.prototype.$;Z.prototype.getObject=Z.prototype.ca;Z.prototype.releaseObject=Z.prototype.hb;U.prototype.listenOnce=U.prototype.Ia;U.prototype.getLastError=U.prototype.$a;U.prototype.getLastErrorCode=U.prototype.Ga;\nU.prototype.getStatus=U.prototype.V;U.prototype.getStatusText=U.prototype.Ha;U.prototype.getResponseJson=U.prototype.Za;U.prototype.getResponseText=U.prototype.U;U.prototype.getResponseText=U.prototype.U;U.prototype.send=U.prototype.ta;module.exports={createWebChannelTransport:Fe,ErrorCode:yc,EventType:zc,WebChannel:Dd,XhrIoPool:Z};}).call(typeof window !== 'undefined' ? window : this)\n\n\n/***/ })\n\n},[113]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-firestore.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-firestore.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/firestore');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./firestore/index.js\n// module id = 113\n// module chunks = 1","/**\n * Copyright 2017 Google Inc.\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/* tslint:disable:no-console */\nimport { SDK_VERSION } from '../core/version';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel = LogLevel || (LogLevel = {}));\nvar logLevel = LogLevel.ERROR;\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel() {\n return logLevel;\n}\nexport function setLogLevel(newLevel) {\n logLevel = newLevel;\n}\nexport function debug(tag, msg) {\n var obj = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n if (logLevel <= LogLevel.DEBUG) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.log.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \" [\" + tag + \"]: \" + msg].concat(args));\n }\n}\nexport function error(msg) {\n var obj = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n if (logLevel <= LogLevel.ERROR) {\n var time = new Date().toISOString();\n var args = obj.map(argToString);\n console.error.apply(console, [\"Firestore (\" + SDK_VERSION + \") \" + time + \": \" + msg].concat(args));\n }\n}\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n }\n else {\n try {\n return JSON.stringify(obj);\n }\n catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n\n//# sourceMappingURL=log.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/log.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SDK_VERSION } from '../core/version';\nimport { error } from './log';\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n error(message);\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 new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nexport function assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n\n//# sourceMappingURL=assert.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/assert.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nvar PlatformSupport = /** @class */ (function () {\n function PlatformSupport() {\n }\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n };\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n };\n return PlatformSupport;\n}());\nexport { PlatformSupport };\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nexport function emptyByteString() {\n return PlatformSupport.getPlatform().emptyByteString;\n}\n\n//# sourceMappingURL=platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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// We are doing some heavy reflective stuff, lots of any casting necessary\n/* tslint:disable:no-any */\nimport { Code, FirestoreError } from './error';\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nexport function makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n // Copy any static methods/members\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n return PublicConstructor;\n}\n\n//# sourceMappingURL=api.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/api.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from './assert';\nexport function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nexport function get(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\nexport function size(obj) {\n var count = 0;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nexport function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\nexport function forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = parseInt(key, 10);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\nexport function forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\nexport function lookupOrInsert(obj, key, valFn) {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\nexport function isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nexport function shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=obj.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as obj from './obj';\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nexport function validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nexport function validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nexport function validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nexport function validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nexport function validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nexport function validateOptionNames(functionName, options, optionNames) {\n obj.forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nexport function invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/input_validation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from './assert';\n// tslint:disable-next-line:class-as-namespace\nvar AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\nexport { AutoId };\nexport function primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using equals(). */\nexport function equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.equals(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using equals(). */\nexport function arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].equals(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nexport function immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/misc.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._equals = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\nexport { Blob };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nexport var PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/blob.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { DocumentKey } from './document_key';\nexport var TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder = TypeOrder || (TypeOrder = {}));\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\nexport { FieldValue };\nvar NullValue = /** @class */ (function (_super) {\n __extends(NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function () {\n return null;\n };\n NullValue.prototype.equals = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(FieldValue));\nexport { NullValue };\nvar BooleanValue = /** @class */ (function (_super) {\n __extends(BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function () {\n return this.internalValue;\n };\n BooleanValue.prototype.equals = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(FieldValue));\nexport { BooleanValue };\n/** Base class for IntegerValue and DoubleValue. */\nvar NumberValue = /** @class */ (function (_super) {\n __extends(NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function () {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(FieldValue));\nexport { NumberValue };\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar IntegerValue = /** @class */ (function (_super) {\n __extends(IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.equals = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via equals().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(NumberValue));\nexport { IntegerValue };\nvar DoubleValue = /** @class */ (function (_super) {\n __extends(DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.equals = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via equals().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue));\nexport { DoubleValue };\n// TODO(b/37267885): Add truncation support\nvar StringValue = /** @class */ (function (_super) {\n __extends(StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function () {\n return this.internalValue;\n };\n StringValue.prototype.equals = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(FieldValue));\nexport { StringValue };\nvar TimestampValue = /** @class */ (function (_super) {\n __extends(TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function () {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.equals = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.equals(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(FieldValue));\nexport { TimestampValue };\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they evaluate to null.\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\nvar ServerTimestampValue = /** @class */ (function (_super) {\n __extends(ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function () {\n return null;\n };\n ServerTimestampValue.prototype.equals = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.equals(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(FieldValue));\nexport { ServerTimestampValue };\nvar BlobValue = /** @class */ (function (_super) {\n __extends(BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function () {\n return this.internalValue;\n };\n BlobValue.prototype.equals = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue._equals(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(FieldValue));\nexport { BlobValue };\nvar RefValue = /** @class */ (function (_super) {\n __extends(RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function () {\n return this.key;\n };\n RefValue.prototype.equals = function (other) {\n if (other instanceof RefValue) {\n return (this.key.equals(other.key) && this.databaseId.equals(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(FieldValue));\nexport { RefValue };\nvar GeoPointValue = /** @class */ (function (_super) {\n __extends(GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function () {\n return this.internalValue;\n };\n GeoPointValue.prototype.equals = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue._equals(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(FieldValue));\nexport { GeoPointValue };\nvar ObjectValue = /** @class */ (function (_super) {\n __extends(ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function () {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value();\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.equals = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.equals(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\n return ObjectValue;\n}(FieldValue));\nexport { ObjectValue };\nvar ArrayValue = /** @class */ (function (_super) {\n __extends(ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function () {\n return this.internalValue.map(function (v) { return v.value(); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.equals = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].equals(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(FieldValue));\nexport { ArrayValue };\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/field_value.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nexport var isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value) {\n return value === null || value === undefined;\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 */\nexport function isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nexport function safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DoubleValue, NullValue, RefValue } from '../model/field_value';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\nvar Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\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 if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.equals(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof RelationFilter) ||\n !filter.isInequality() ||\n filter.field.equals(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\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.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.equals = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].equals(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].equals(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.equals(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.equals(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.equals(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.equals(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\nexport { Query };\nvar RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.equals = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\nexport { RelationOp };\nvar RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case RelationOp.LESS_THAN:\n return comparison < 0;\n case RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case RelationOp.EQUAL:\n return comparison === 0;\n case RelationOp.GREATER_THAN:\n return comparison > 0;\n case RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\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 (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.equals = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.equals(other.op) &&\n this.field.equals(other.field) &&\n this.value.equals(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\nexport { RelationFilter };\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.equals = function (other) {\n if (other instanceof NullFilter) {\n return this.field.equals(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\nexport { NullFilter };\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.equals = function (other) {\n if (other instanceof NanFilter) {\n return this.field.equals(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\nexport { NanFilter };\n/**\n * Creates a filter based on the provided arguments.\n */\nexport function fieldFilter(field, op, value) {\n if (value.equals(NullValue.INSTANCE)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.equals(DoubleValue.NAN)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\nexport { Direction };\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 */\nvar Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.equals = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.equals(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\nexport { Bound };\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? Document.compareByKey(d1, d2)\n : Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.equals = function (other) {\n return this.dir === other.dir && this.field.equals(other.field);\n };\n return OrderBy;\n}());\nexport { OrderBy };\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/query.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\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.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nexport function isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\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 */\nexport function mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\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 */\nexport function mapCodeFromRpcCode(code) {\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/rpc_error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { DocumentKey } from './document_key';\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/collections.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\nimport { assert, fail } from '../util/assert';\nimport * as objUtils from '../util/obj';\nimport { CurrentStatusUpdate, RemoteEvent, ResetMapping, UpdateMapping } from './remote_event';\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 */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \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 newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\nexport { DocumentWatchChange };\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\nexport { ExistenceFilterChange };\nexport var WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState = WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\nexport { WatchTargetChange };\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = objUtils.shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n objUtils.forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!objUtils.contains(this.pendingTargetResponses, targetId) &&\n objUtils.contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!objUtils.contains(_this.pendingTargetResponses, targetId)) {\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 change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\nexport { WatchChangeAggregator };\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/watch_change.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Blob } from '../api/blob';\nimport { GeoPoint } from '../api/geo_point';\nimport { DatabaseId } from '../core/database_info';\nimport { Bound, Direction, NanFilter, NullFilter, OrderBy, Query, RelationFilter, RelationOp } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { QueryPurpose } from '../local/query_data';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport * as fieldValue from '../model/field_value';\nimport { DeleteMutation, FieldMask, FieldTransform, MutationResult, PatchMutation, Precondition, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as obj from '../util/obj';\nimport * as typeUtils from '../util/types';\nimport { ExistenceFilter } from './existence_filter';\nimport { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';\nimport { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return parseInt(value, 10);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\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 (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof fieldValue.NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof fieldValue.BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof fieldValue.IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof fieldValue.DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof fieldValue.StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof fieldValue.ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof fieldValue.ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof fieldValue.TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof fieldValue.GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof fieldValue.BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof fieldValue.RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return fieldValue.NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return fieldValue.BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new fieldValue.IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return fieldValue.DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return fieldValue.DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return fieldValue.DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new fieldValue.DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new fieldValue.StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new fieldValue.ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new fieldValue.TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new fieldValue.BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new fieldValue.RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = fieldValue.ObjectValue.EMPTY;\n obj.forEach(map, function (key, value) {\n result = result.set(new FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result_type'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['change_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : SnapshotVersion.forDeletedDoc();\n var doc = new NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\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 // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n }\n else {\n return Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toLimit(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = query.limit;\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toLimit = function (limit) {\n if (!typeUtils.isNullOrUndefined(limit)) {\n return limit;\n }\n return;\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return RelationOp.EQUAL;\n case 'GREATER_THAN':\n return RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return FieldPath.fromServerFormat(path); });\n return new FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\nexport { JsonProtoSerializer };\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateArgType, validateNamedArrayAtLeastNumberOfElements } from '../util/input_validation';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar FieldPath = /** @class */ (function () {\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 function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(InternalFieldPath.keyField().canonicalString());\n return FieldPath;\n}());\nexport { FieldPath };\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nexport function fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (FieldPath.bind.apply(FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentSet } from '../model/document_set';\nimport { CurrentStatusUpdate, ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport { ChangeType, DocumentChangeSet, SyncState } from './view_snapshot';\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\nexport { AddedLimboDocument };\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\n}());\nexport { RemovedLimboDocument };\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 */\nvar View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\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 = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\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 * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\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 //\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 var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.equals(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.equals(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\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 needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n var limboChanges = this.applyTargetChange(targetChange);\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n return {\n snapshot: {\n query: this.query,\n docs: docChanges.documentSet,\n oldDocs: oldDocs,\n docChanges: changes,\n fromCache: newSyncState === SyncState.Local,\n syncStateChanged: syncStateChanged,\n hasPendingWrites: !docChanges.mutatedKeys.isEmpty()\n },\n limboChanges: limboChanges\n };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\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 */\n View.prototype.applyTargetChange = function (targetChange) {\n var _this = this;\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n // Recompute the set of limbo docs.\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n if (this.current) {\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n }\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\nexport { View };\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case 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 case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\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 */\nexport function decode(path) {\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 var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\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 var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nexport function prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/encoded_resource_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { encode } from './encoded_resource_path';\nexport var SCHEMA_VERSION = 1;\n/** Performs database creation and (in the future) upgrades between versions. */\nexport function createOrUpgradeDb(db, oldVersion) {\n assert(oldVersion === 0, 'Unexpected upgrade from version ' + oldVersion);\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n // TODO(mikelehen): Get rid of \"as any\" if/when TypeScript fixes their\n // types. https://github.com/Microsoft/TypeScript/issues/14322\n db.createObjectStore(\n // tslint:disable-next-line:no-any\n DbMutationBatch.store, { keyPath: DbMutationBatch.keyPath });\n var targetDocumentsStore = db.createObjectStore(\n // tslint:disable-next-line:no-any\n DbTargetDocument.store, { keyPath: DbTargetDocument.keyPath });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n // NOTE: keys for these stores are specified explicitly rather than using a\n // keyPath.\n db.createObjectStore(DbDocumentMutation.store);\n db.createObjectStore(DbRemoteDocument.store);\n db.createObjectStore(DbOwner.store);\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\nexport { DbTimestamp };\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\nexport { DbOwner };\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\nexport { DbMutationQueue };\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\nexport { DbMutationBatch };\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\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 DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\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 */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\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 */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\nexport { DbDocumentMutation };\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\nexport { DbNoDocument };\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\nexport { DbRemoteDocument };\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\nexport { DbTarget };\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\nexport { DbTargetDocument };\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\nexport { DbTargetGlobal };\n/**\n * The list of all IndexedDB stored used by the SDK. This is used when creating\n * transactions so that access across all stores is done atomically.\n */\nexport var ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_schema.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { PersistencePromise } from './persistence_promise';\nvar LOG_TAG = 'SimpleDb';\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 */\nvar SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(LOG_TAG, 'Opening database:', name);\n return new PersistencePromise(function (resolve, reject) {\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.\n var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n // TODO(mikelehen): If/when we need to do an actual data\n // migration, we'll want to wrap db in a SimpleDb and have the\n // runUpgrade function return a PersistencePromise, since we'll\n // likely need to do async reads and writes. For now we're\n // cheating and just passing the raw IndexedDB in, since\n // createObjectStore(), etc. are synchronous.\n var db = event.target.result;\n runUpgrade(db, event.oldVersion);\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\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 var ua = window.navigator.userAgent;\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 if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = new SimpleDbTransaction(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return PersistencePromise.reject(error);\n })\n .toPromise();\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 return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\n}());\nexport { SimpleDb };\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 */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\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 */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\nexport { IterationController };\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(db, mode, objectStoresNames) {\n var _this = this;\n this.aborted = false;\n this.transaction = db.transaction(objectStoresNames, mode);\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore 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 */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n };\n return SimpleDbTransaction;\n}());\nexport { SimpleDbTransaction };\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 */\nvar SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\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 * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\nexport { SimpleDbStore };\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/simple_db.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { immediatePredecessor, primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbDocumentMutation, DbMutationBatch, DbMutationQueue } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\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 */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\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 assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isUnauthenticated() ? '' : user.uid;\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var encodedPath = EncodedResourcePath.encode(mutation.key.path);\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, DbDocumentMutation.PLACEHOLDER);\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(batchId + 1));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId > batchId, 'Should have found mutation after ' + batchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\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 var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.equals(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var encodedQueryPath = indexPrefix[1];\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\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 var uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\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 if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = EncodedResourcePath.decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, _, control) {\n var userID = key[0], keyPath = key[1], batchID = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\nexport { IndexedDbMutationQueue };\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, SnapshotVersion.MIN.toTimestamp());\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n if (metadata !== null) {\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = SnapshotVersion.fromTimestamp(new Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n }\n return PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n var targetId = queryData.targetId;\n var addedQueryPromise = targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n if (targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = targetId;\n return addedQueryPromise.next(function () {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, _this.metadata);\n });\n }\n else {\n return addedQueryPromise;\n }\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId).next(function () {\n targetsStore(transaction).delete(queryData.targetId);\n });\n };\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\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 efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.equals(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var promises = [];\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = EncodedResourcePath.encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\nexport { IndexedDbQueryCache };\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { fail } from '../util/assert';\nimport { DbRemoteDocument } from './indexeddb_schema';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\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 var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\nexport { IndexedDbRemoteDocumentCache };\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { DbMutationBatch, DbNoDocument, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema';\nimport { QueryData, QueryPurpose } from './query_data';\n/** Serializer for values stored in the LocalStore. */\nvar LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new Timestamp(readTime.seconds, readTime.nanos);\n return new NoDocument(key, SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\nexport { LocalSerializer };\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { User } from '../auth/user';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\nexport { OAuthToken };\n/** A CredentialsProvider that always yields an empty token. */\nvar EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\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.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\nexport { EmptyCredentialsProvider };\nvar FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.equals(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\n}());\nexport { FirebaseCredentialsProvider };\n// Wrap a google-auth-library client as a CredentialsProvider.\n// NOTE: grpc-connection can natively accept a google-auth-library\n// client via createFromGoogleCredential(), but we opt to plumb the tokens\n// through our CredentialsProvider interface, at least for now.\nvar GoogleCredentialsProvider = /** @class */ (function () {\n function GoogleCredentialsProvider(authClient) {\n this.authClient = authClient;\n }\n GoogleCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n // TODO(b/32935141): ideally this would be declared as an extern\n _this.authClient['getAccessToken'](function (error, tokenLiteral) {\n if (error) {\n reject(error);\n }\n else {\n resolve(new OAuthToken(tokenLiteral, User.GOOGLE_CREDENTIALS));\n }\n });\n });\n };\n // NOTE: A google-auth-library client represents an immutable \"user\", so\n // once we fire the initial event, it'll never change.\n GoogleCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.GOOGLE_CREDENTIALS);\n };\n GoogleCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return GoogleCredentialsProvider;\n}());\nexport { GoogleCredentialsProvider };\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 * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\n}());\nexport { FirstPartyToken };\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 */\nvar FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\nexport { FirstPartyCredentialsProvider };\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'google-auth':\n return new GoogleCredentialsProvider(credentials.client);\n case 'gapi':\n return new FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/credentials.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport function isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Timestamp } from '../core/timestamp';\nimport { ObjectValue } from '../model/field_value';\nimport { ArrayValue, BlobValue, BooleanValue, DoubleValue, GeoPointValue, IntegerValue, NullValue, RefValue, StringValue, TimestampValue } from '../model/field_value';\nimport { FieldMask, FieldTransform, PatchMutation, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport * as typeUtils from '../util/types';\nimport { Blob } from './blob';\nimport { FieldPath as ExternalFieldPath, fromDotSeparatedString } from './field_path';\nimport { DeleteFieldValueImpl, FieldValueImpl, ServerTimestampFieldValueImpl } from './field_value';\nimport { GeoPoint } from './geo_point';\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\nexport { ParsedSetData };\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\nexport { ParsedUpdateData };\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * 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 function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n ParseContext.prototype.isWrite = function () {\n return (this.dataSource === UserDataSource.Set ||\n this.dataSource === UserDataSource.Update);\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\nexport { DocumentKeyReference };\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call.*/\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new FieldMask(context.fieldMask);\n return new ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n objUtils.forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new ParseContext(UserDataSource.QueryValue, methodName, FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\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 * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new SortedMap(primitiveComparator);\n objUtils.forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (typeUtils.isSafeInteger(value)) {\n return new IntegerValue(value);\n }\n else {\n return new DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new StringValue(value);\n }\n else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\n }\n else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n }\n else if (value instanceof Blob) {\n return new BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource == UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\nexport { UserDataConverter };\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 */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(methodName, path) {\n if (path instanceof ExternalFieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\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 split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/user_data_converter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { FieldPath as ExternalFieldPath } from './field_path';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { FirestoreClient } from '../core/firestore_client';\nimport { Bound, Direction, fieldFilter, OrderBy, Query as InternalQuery, RelationFilter, RelationOp } from '../core/query';\nimport { ChangeType } from '../core/view_snapshot';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ArrayValue, ObjectValue, RefValue } from '../model/field_value';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { assert, fail } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateAtLeastNumberOfArgs, validateBetweenNumberOfArgs, validateDefined, validateExactNumberOfArgs, validateNamedOptionalType, validateNamedType, validateOptionalArgType, validateOptionNames, valueDescription } from '../util/input_validation';\nimport * as log from '../util/log';\nimport { LogLevel } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { EmptyCredentialsProvider, FirebaseCredentialsProvider, makeCredentialsProvider } from './credentials';\nimport { isPartialObserver } from './observer';\nimport { DocumentKeyReference, fieldPathFromArgument, UserDataConverter } from './user_data_converter';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.equals = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n this.INTERNAL = {\n delete: function () {\n if (_this._firestoreClient) {\n return _this._firestoreClient.shutdown();\n }\n else {\n return Promise.resolve();\n }\n },\n // Exposed via INTERNAL for use in tests.\n disableNetwork: function () { return _this._firestoreClient.disableNetwork(); },\n enableNetwork: function () { return _this._firestoreClient.enableNetwork(); }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new EmptyCredentialsProvider();\n }\n config.settings = new FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (objUtils.contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.equals(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.equals(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new UserDataConverter(preConverter);\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, new AsyncQueue());\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!objUtils.contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (objUtils.contains(options, 'firestoreId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (objUtils.contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (log.getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + log.getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n log.setLogLevel(log.LogLevel.DEBUG);\n break;\n case 'error':\n log.setLogLevel(log.LogLevel.ERROR);\n break;\n case 'silent':\n log.setLogLevel(log.LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\nexport { Firestore };\n/**\n * A reference to a transaction.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\nexport { Transaction };\nvar WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n else {\n return Promise.resolve();\n }\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\nexport { WriteBatch };\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.equals(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new DeleteMutation(this._key, Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(InternalQuery.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.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 reject(new FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\nexport { DocumentReference };\nvar DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function () {\n validateExactNumberOfArgs('DocumentSnapshot.data', arguments, 0);\n if (!this._document) {\n throw new FirestoreError(Code.NOT_FOUND, \"This document doesn't exist. Check doc.exists to make sure \" +\n 'the document exists before calling doc.data().');\n }\n return this.convertObject(this._document.data);\n };\n DocumentSnapshot.prototype.get = function (fieldPath) {\n validateExactNumberOfArgs('DocumentSnapshot.get', arguments, 1);\n if (!this._document) {\n throw new FirestoreError(Code.NOT_FOUND, \"This document doesn't exist. Check doc.exists to make sure \" +\n 'the document exists before calling doc.get().');\n }\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n return value === undefined ? undefined : this.convertValue(value);\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return {\n hasPendingWrites: this._document !== null && this._document.hasLocalMutations,\n fromCache: this._fromCache\n };\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.convertObject = function (data) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value) {\n if (value instanceof ObjectValue) {\n return this.convertObject(value);\n }\n else if (value instanceof ArrayValue) {\n return this.convertArray(value);\n }\n else if (value instanceof RefValue) {\n var key = value.value();\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.equals(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log.error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId\n .database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new DocumentReference(key, this._firestore);\n }\n else {\n return value.value();\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value);\n });\n };\n return DocumentSnapshot;\n}());\nexport { DocumentSnapshot };\nvar Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\n }\n else if (value instanceof DocumentReference) {\n var ref = value;\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.equals(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\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.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\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 (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new DocumentKey(this._query.path.child(rawValue));\n components.push(new RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.equals(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.equals(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\nexport { Query };\nvar QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = {\n fromCache: _snapshot.fromCache,\n hasPendingWrites: _snapshot.hasPendingWrites\n };\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new DocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\nexport { QuerySnapshot };\nvar CollectionReference = /** @class */ (function (_super) {\n __extends(CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, InternalQuery.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = ResourcePath.fromString(pathString);\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(Query));\nexport { CollectionReference };\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nexport function changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new DocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new DocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nexport var PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\nexport var PublicTransaction = makeConstructorPrivate(Transaction, 'Use firebase.firestore().runTransaction() instead.');\nexport var PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\nexport var PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\nexport var PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nexport var PublicQuery = makeConstructorPrivate(Query);\nexport var PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nexport var PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/database.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PublicBlob } from '../api/blob';\nimport { Firestore, PublicCollectionReference, PublicDocumentReference, PublicDocumentSnapshot, PublicFirestore, PublicQuery, PublicQuerySnapshot, PublicTransaction, PublicWriteBatch } from '../api/database';\nimport { FieldPath } from '../api/field_path';\nimport { PublicFieldValue } from '../api/field_value';\nimport { GeoPoint } from '../api/geo_point';\nimport { shallowCopy } from '../util/obj';\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nexport function configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nexport function configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/config.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport './src/platform_browser/browser_init';\nimport { configureForFirebase } from './src/platform/config';\nexport function registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\n/** The semver (www.semver.org) version of the SDK. */\nexport var SDK_VERSION = firebase.SDK_VERSION;\n\n//# sourceMappingURL=version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\nexport var Code = {\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 class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nvar FirestoreError = /** @class */ (function (_super) {\n __extends(FirestoreError, _super);\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError';\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 = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\n return _this;\n }\n return FirestoreError;\n}(Error));\nexport { FirestoreError };\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Code, FirestoreError } from '../util/error';\nimport { validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._equals = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\nexport { GeoPoint };\n\n//# sourceMappingURL=geo_point.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/geo_point.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { primitiveComparator } from '../util/misc';\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\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 */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\nexport { DatabaseInfo };\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.equals = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\nexport { DatabaseId };\n\n//# sourceMappingURL=database_info.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/database_info.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nexport var DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.equals = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\nexport { Path };\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar ResourcePath = /** @class */ (function (_super) {\n __extends(ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\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 ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\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 if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(Path));\nexport { ResourcePath };\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar FieldPath = /** @class */ (function (_super) {\n __extends(FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_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 */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(Path));\nexport { FieldPath };\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { ResourcePath } from './path';\nvar DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.equals = function (other) {\n return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\n return DocumentKey;\n}());\nexport { DocumentKey };\n\n//# sourceMappingURL=document_key.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_key.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\nimport { DocumentKey } from './document_key';\nvar Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.equals = function (other) {\n return (other instanceof Document &&\n this.key.equals(other.key) &&\n this.version.equals(other.version) &&\n this.data.equals(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\nexport { Document };\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.equals = function (other) {\n return (other && other.version.equals(this.version) && other.key.equals(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\nexport { NoDocument };\n\n//# sourceMappingURL=document.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert, fail } from './assert';\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n // Returns the key of the item *before* the specified key, or null if key is\n // the first item.\n SortedMap.prototype.getPredecessorKey = function (key) {\n var node = this.root;\n var rightParent = null;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw fail('Attempted to find predecessor key for a nonexistent key.' +\n ' What gives?');\n };\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\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 SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\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 SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root, null, this.comparator, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root, key, this.comparator, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root, null, this.comparator, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root, key, this.comparator, true, resultGenerator);\n };\n return SortedMap;\n}()); // end SortedMap\nexport { SortedMap };\n// An iterator over an LLRBNode.\nvar SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse, resultGenerator) {\n this.resultGenerator = resultGenerator || null;\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\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(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result;\n if (this.resultGenerator)\n result = this.resultGenerator(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n if (this.resultGenerator) {\n return this.resultGenerator(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\nexport { SortedMapIterator };\n// Represents a node in a Left-leaning Red-Black tree.\nvar LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\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 LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\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 LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\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 LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\nexport { LLRBNode };\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\nexport { LLRBEmptyNode };\nLLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { emptyByteString } from '../platform/platform';\n/** An enumeration of the different purposes we have for queries. */\nexport var QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose = QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.equals = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.equals(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.equals(other.query));\n };\n return QueryData;\n}());\nexport { QueryData };\n\n//# sourceMappingURL=query_data.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/query_data.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\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 var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = parseInt(nanoStr, 10);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.equals = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\nexport { Timestamp };\n\n//# sourceMappingURL=timestamp.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/timestamp.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Timestamp } from './timestamp';\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.equals = function (other) {\n return this.timestamp.equals(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\n return SnapshotVersion;\n}());\nexport { SnapshotVersion };\n\n//# sourceMappingURL=snapshot_version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/snapshot_version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { Document, NoDocument } from './document';\nimport { ObjectValue, ServerTimestampValue } from './field_value';\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 */\nvar FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.equals = function (other) {\n return misc.arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\nexport { FieldMask };\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.equals = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\nexport { ServerTimestampTransform };\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.equals = function (other) {\n return (this.field.equals(other.field) && this.transform.equals(other.transform));\n };\n return FieldTransform;\n}());\nexport { FieldTransform };\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\nexport { MutationResult };\nexport var MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType = MutationType || (MutationType = {}));\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 */\nvar Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof Document && maybeDoc.version.equals(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.equals = function (other) {\n return (misc.equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\n}());\nexport { Precondition };\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 it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we 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 null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.equals(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n }\n else {\n return SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\nexport { Mutation };\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar SetMutation = /** @class */ (function (_super) {\n __extends(SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\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 var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.equals = function (other) {\n return (other instanceof SetMutation &&\n this.key.equals(other.key) &&\n this.value.equals(other.value) &&\n this.precondition.equals(other.precondition));\n };\n return SetMutation;\n}(Mutation));\nexport { SetMutation };\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 */\nvar PatchMutation = /** @class */ (function (_super) {\n __extends(PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.equals = function (other) {\n return (other instanceof PatchMutation &&\n this.key.equals(other.key) &&\n this.fieldMask.equals(other.fieldMask) &&\n this.precondition.equals(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data;\n }\n else {\n data = ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(Mutation));\nexport { PatchMutation };\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar TransformMutation = /** @class */ (function (_super) {\n __extends(TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.equals = function (other) {\n return (other instanceof TransformMutation &&\n this.key.equals(other.key) &&\n misc.arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.equals(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.equals(this.key), 'Can only transform a document with the same key');\n return doc;\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 * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n transformResults.push(new ServerTimestampValue(localWriteTime));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(Mutation));\nexport { TransformMutation };\n/** A mutation that deletes the document at the given key. */\nvar DeleteMutation = /** @class */ (function (_super) {\n __extends(DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\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 return new NoDocument(this.key, SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.equals(this.key), 'Can only apply mutation to document with same key');\n }\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.equals = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.equals(other.key) &&\n this.precondition.equals(other.precondition));\n };\n return DeleteMutation;\n}(Mutation));\nexport { DeleteMutation };\n\n//# sourceMappingURL=mutation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.equals = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\nexport { ExistenceFilter };\n\n//# sourceMappingURL=existence_filter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/existence_filter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SortedMap } from './sorted_map';\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 */\nvar SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.equals = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\nexport { SortedSet };\n\n//# sourceMappingURL=sorted_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\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 */\nvar RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \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 documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\nexport { RemoteEvent };\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nexport var CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate = CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.equals = function (other) {\n return other !== null && this.docs.equals(other.docs);\n };\n return ResetMapping;\n}());\nexport { ResetMapping };\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.equals = function (other) {\n return (other !== null &&\n this.addedDocuments.equals(other.addedDocuments) &&\n this.removedDocuments.equals(other.removedDocuments));\n };\n return UpdateMapping;\n}());\nexport { UpdateMapping };\n\n//# sourceMappingURL=remote_event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_event.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\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 */\nvar StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.wrappedOnOpen = null;\n this.wrappedOnClose = null;\n this.wrappedOnMessage = null;\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== null, 'Cannot call onOpen because no callback ' + 'was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== null, 'Cannot call onClose because no ' + 'callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== null, 'Cannot call onMessage because no ' + 'callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\nexport { StreamBridge };\n\n//# sourceMappingURL=stream_bridge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/stream_bridge.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ErrorCode, EventType, WebChannel, XhrIoPool, createWebChannelTransport } from '@firebase/webchannel-wrapper';\nimport { SDK_VERSION } from '../core/version';\nimport { mapCodeFromHttpStatus, mapCodeFromRpcStatus } from '../remote/rpc_error';\nimport { StreamBridge } from '../remote/stream_bridge';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nvar LOG_TAG = 'Connection';\nvar RPC_URL_VERSION = 'v1beta1';\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new XhrIoPool();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n // This header is used to improve routing and project isolation by the\n // backend.\n headers['google-cloud-resource-prefix'] =\n \"projects/\" + this.databaseId.projectId + \"/\" +\n (\"databases/\" + this.databaseId.database);\n };\n WebChannelConnection.prototype.invoke = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(EventType.COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n var json = xhr.getResponseJson();\n log.debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n log.error('RPC \"' + rpcName + '\" timed out, retrying.');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case ErrorCode.HTTP_ERROR:\n var status_1 = xhr.getStatus();\n log.error('RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue, let's retry.\n log.error(LOG_TAG, 'RPC \"' + rpcName + '\" failed, retrying.');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n log.debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var rpcService = WebChannelConnection.RPC_STREAM_SERVICE_MAPPING[rpcName];\n var rpcUrlName = WebChannelConnection.RPC_STREAM_NAME_MAPPING[rpcName];\n if (!rpcService || !rpcUrlName) {\n fail('Unknown RPC name: ' + rpcName);\n }\n var urlParts = [\n this.baseUrl,\n '/',\n rpcService,\n '/',\n rpcUrlName,\n '/channel'\n ];\n var webchannelTransport = createWebChannelTransport();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n sendRawJson: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n log.debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\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 var opened = false;\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 var closed = false;\n // tslint:disable-next-line:no-any\n var streamBridge = new StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n log.debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n log.debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n log.debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\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 var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(WebChannel.EventType.OPEN, function () {\n if (!closed) {\n log.debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(WebChannel.EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(WebChannel.EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(WebChannel.EventType.MESSAGE, function (msg) {\n if (!closed) {\n // WebChannel delivers message events as array. If batching\n // is not enabled (it's off by default) each message will be\n // delivered alone, resulting in a single element array.\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\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 var error = msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n log.debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n }\n else {\n log.debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\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 streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(rpcName);\n return url.join('');\n };\n /**\n * Mapping from RPC name to service providing the RPC.\n * For streaming RPCs only.\n */\n WebChannelConnection.RPC_STREAM_SERVICE_MAPPING = {\n Write: 'google.firestore.v1beta1.Firestore',\n Listen: 'google.firestore.v1beta1.Firestore'\n };\n /**\n * Mapping from RPC name to actual RPC name in URLs.\n * For streaming RPCs only.\n */\n WebChannelConnection.RPC_STREAM_NAME_MAPPING = {\n Write: 'Write',\n Listen: 'Listen'\n };\n return WebChannelConnection;\n}());\nexport { WebChannelConnection };\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { WebChannelConnection } from './webchannel_connection';\nvar BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\nexport { BrowserPlatform };\n\n//# sourceMappingURL=browser_platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PlatformSupport } from '../platform/platform';\nimport { BrowserPlatform } from './browser_platform';\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nPlatformSupport.setPlatform(new BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_init.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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/** Describes the online state of the Firestore client */\nexport var OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it was\n * previously in an unknown state and is trying to establish a connection.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * succesful message received from the backends.\n */\n OnlineState[OnlineState[\"Healthy\"] = 1] = \"Healthy\";\n /**\n * The client has tried to establish a connection but has failed.\n * This state is reached after either a connection attempt failed or a\n * healthy stream was closed for unexpected reasons.\n */\n OnlineState[OnlineState[\"Failed\"] = 2] = \"Failed\";\n})(OnlineState = OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nexport var ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType = ChangeType || (ChangeType = {}));\nexport var SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState = SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new SortedMap(DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\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('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\nexport { DocumentChangeSet };\n\n//# sourceMappingURL=view_snapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view_snapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\nexport { TargetIdGenerator };\n\n//# sourceMappingURL=target_id_generator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/target_id_generator.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nimport { documentMap } from './collections';\nimport { DocumentKey } from './document_key';\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 */\nvar DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\n return this.sortedSet.isEmpty();\n };\n /**\n * Returns previous document or null if it's a first doc.\n *\n * @param key A key that MUST be present in the DocumentSet.\n */\n DocumentSet.prototype.prevDoc = function (key) {\n assert(this.has(key), 'Trying to get a previous document to non-existing key: ' + key);\n var doc = this.keyedMap.get(key);\n return this.sortedSet.getPredecessorKey(doc);\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 */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.equals = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.equals(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\nexport { DocumentSet };\n\n//# sourceMappingURL=document_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as objUtil from './obj';\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.equals(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].equals(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].equals(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n objUtil.forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return objUtil.isEmpty(this.inner);\n };\n return ObjectMap;\n}());\nexport { ObjectMap };\n\n//# sourceMappingURL=obj_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { OnlineState } from './types';\nimport { ChangeType } from './view_snapshot';\nimport { DocumentSet } from '../model/document_set';\nimport { assert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.onOnlineStateChanged(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n var query = listener.query;\n var lastListen = false;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n var i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n else {\n return Promise.resolve();\n }\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.onOnlineStateChanged = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onOnlineStateChanged(onlineState);\n }\n });\n };\n return EventManager;\n}());\nexport { EventManager };\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 */\nvar QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\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.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = {\n query: snap.query,\n docs: snap.docs,\n oldDocs: snap.oldDocs,\n docChanges: docChanges,\n fromCache: snap.fromCache,\n hasPendingWrites: snap.hasPendingWrites,\n syncStateChanged: snap.syncStateChanged\n };\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.onOnlineStateChanged = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Failed\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Failed;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Failed;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\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 (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\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 return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = {\n query: snap.query,\n docs: snap.docs,\n oldDocs: DocumentSet.emptySet(snap.docs),\n docChanges: QueryListener.getInitialViewChanges(snap),\n fromCache: snap.fromCache,\n hasPendingWrites: snap.hasPendingWrites,\n syncStateChanged: true\n };\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\nexport { QueryListener };\n\n//# sourceMappingURL=event_manager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/event_manager.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\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 */\nvar PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\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;\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = null;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_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(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\nexport { PersistencePromise };\n\n//# sourceMappingURL=persistence_promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/persistence_promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\nexport { EagerGarbageCollector };\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/eager_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ChangeType } from '../core/view_snapshot';\nimport { documentKeySet } from '../model/collections';\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 */\nvar LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\nexport { LocalViewChanges };\n\n//# sourceMappingURL=local_view_changes.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_view_changes.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\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 */\nvar ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new SortedSet(DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(firstRef !== null && key.equals(firstRef.key));\n };\n return ReferenceSet;\n}());\nexport { ReferenceSet };\nvar DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\nexport { DocReference };\n\n//# sourceMappingURL=reference_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/reference_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { ExponentialBackoff } from './backoff';\nvar LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\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 *\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\n * onClose 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 */\nvar PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connection, credentialsProvider, listener, \n // Used for faster retries in testing\n initialBackoffDelay) {\n this.queue = queue;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.stream = null;\n this.listener = null;\n this.backoff = new ExponentialBackoff(initialBackoffDelay ? initialBackoffDelay : BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\n this.listener = listener;\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 */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\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 ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function () {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.auth();\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 */\n PersistentStream.prototype.stop = function () {\n // Prevent any possible future restart of this stream\n this.state = PersistentStreamState.Stopped;\n // Clear the listener to avoid bleeding of events from the underlying\n // streams\n this.listener = null;\n // Clean up the underlying stream because we are no longer interested in\n // events\n if (this.stream !== null) {\n this.stream.close();\n this.stream = null;\n }\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 function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\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.startStream(token);\n }, function (error) {\n _this.queue.schedule(function () {\n if (_this.state !== PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return _this.handleStreamClose(rpcError);\n }\n else {\n return Promise.resolve();\n }\n });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfNotStopped = function (fn) {\n _this.queue.schedule(function () {\n // Only raise events if the listener has not changed\n if (_this.state !== PersistentStreamState.Stopped) {\n return fn();\n }\n else {\n return Promise.resolve();\n }\n });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n this.stream = this.startRpc(token);\n this.stream.onOpen(function () {\n dispatchIfNotStopped(function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfNotStopped(function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfNotStopped(function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndWait().then(function () {\n // Backoff does not run on the AsyncQueue, so we need to reschedule to\n // make sure the queue blocks\n _this.queue.schedule(function () {\n if (_this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for backoff to complete.\n return Promise.resolve();\n }\n _this.state = PersistentStreamState.Initial;\n _this.start();\n assert(_this.isStarted(), 'PersistentStream should have started');\n return Promise.resolve();\n });\n });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n log.debug(LOG_TAG, \"close with error: \" + error);\n this.stream = null;\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 this.state = PersistentStreamState.Error;\n if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n log.debug(LOG_TAG, 'Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n return this.listener.onClose(error);\n };\n return PersistentStream;\n}());\nexport { PersistentStream };\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar PersistentListenStream = /** @class */ (function (_super) {\n __extends(PersistentListenStream, _super);\n function PersistentListenStream(databaseInfo, queue, connection, credentials, serializer, listener, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, listener, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.stream.send(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.stream.send(request);\n };\n return PersistentListenStream;\n}(PersistentStream));\nexport { PersistentListenStream };\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 */\nvar PersistentWriteStream = /** @class */ (function (_super) {\n __extends(PersistentWriteStream, _super);\n function PersistentWriteStream(databaseInfo, queue, connection, credentials, serializer, listener, initialBackoffDelay) {\n var _this = _super.call(this, queue, connection, credentials, listener, initialBackoffDelay) || this;\n _this.databaseInfo = databaseInfo;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function () {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this);\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\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.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\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 */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\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 var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.stream.send(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.stream.send(request);\n };\n return PersistentWriteStream;\n}(PersistentStream));\nexport { PersistentWriteStream };\n\n//# sourceMappingURL=persistent_stream.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/persistent_stream.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { ReferenceSet } from '../local/reference_set';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { CurrentStatusUpdate, RemoteEvent } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { isNullOrUndefined } from '../util/types';\nimport { Query } from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { TargetIdGenerator } from './target_id_generator';\nimport { AddedLimboDocument, RemovedLimboDocument, View } from './view';\nvar LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \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 view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new ReferenceSet();\n this.limboCollector = new EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\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 targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\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 */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\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 some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\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 *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\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 var docMap = new SortedMap(DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\n var event_1 = new RemoteEvent(SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\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 this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\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 this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.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 (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n log.debug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n log.debug(LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\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 return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\nexport { SyncEngine };\n\n//# sourceMappingURL=sync_engine.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/sync_engine.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet, documentVersionMap } from './collections';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nexport var BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.equals(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.equals(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.equals(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.equals(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.equals = function (other) {\n return (this.batchId === other.batchId &&\n misc.arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\nexport { MutationBatch };\n/** The result of applying a mutation batch to the backend. */\nvar MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\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=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\nexport { MutationBatchResult };\n\n//# sourceMappingURL=mutation_batch.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation_batch.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbQueryCache } from './indexeddb_query_cache';\nimport { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport { ALL_STORES, DbOwner } from './indexeddb_schema';\nimport { createOrUpgradeDb, SCHEMA_VERSION } from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDb } from './simple_db';\nvar LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n log.debug(LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n log.debug(LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n log.debug(LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n log.debug(LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log.error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log.error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n log.debug(LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error(LOG_TAG, 'Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error(LOG_TAG, 'Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\nexport { IndexedDbPersistence };\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet, documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\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 */\nvar LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\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 */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\nexport { LocalDocumentsView };\n\n//# sourceMappingURL=local_documents_view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_documents_view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\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 * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\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 * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\nexport { RemoteDocumentChangeBuffer };\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { QueryData, QueryPurpose } from './query_data';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nvar LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\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 LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge 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 */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\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 */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update 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 */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.addQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.equals(SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n log.debug(LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\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 var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.equals(SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return PersistencePromise.waitFor(promises);\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 */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (objUtils.isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n objUtils.isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\nexport { LocalStore };\n\n//# sourceMappingURL=local_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\nimport { DocReference } from './reference_set';\nvar MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\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.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\n }\n return PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n batchId = Math.max(batchId + 1, this.highestAcknowledgedBatchId);\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(batchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return PersistencePromise.resolve(batch);\n }\n }\n return PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new DocReference(documentKey, 0);\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.equals(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.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 var startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new DocReference(new DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\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 if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\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 var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.equals(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\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 */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return 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 */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\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 var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\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 */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\nexport { MemoryMutationQueue };\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ObjectMap } from '../util/obj_map';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nvar MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new ReferenceSet();\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\nexport { MemoryQueryCache };\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { PersistencePromise } from './persistence_promise';\nvar MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\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 var prefix = new DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\nexport { MemoryRemoteDocumentCache };\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport { MemoryQueryCache } from './memory_query_cache';\nimport { MemoryRemoteDocumentCache } from './memory_remote_document_cache';\nvar LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new MemoryRemoteDocumentCache();\n this.queryCache = new MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n // No durable state to read on startup.\n return Promise.resolve();\n };\n MemoryPersistence.prototype.shutdown = function () {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return Promise.resolve();\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\nexport { MemoryPersistence };\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\nexport { NoOpGarbageCollector };\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\nexport { Deferred };\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nexport function sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as log from '../util/log';\nimport { Deferred } from '../util/promise';\nvar LOG_TAG = 'ExponentialBackoff';\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 */\nvar ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\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 initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \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 */\n maxDelayMs) {\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n 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 */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\n };\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts.\n */\n ExponentialBackoff.prototype.backoffAndWait = function () {\n var def = new Deferred();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n log.debug(LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n setTimeout(function () {\n def.resolve();\n }, delayWithJitterMs);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n return def.promise;\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\nexport { ExponentialBackoff };\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistentListenStream, PersistentWriteStream } from './persistent_stream';\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar Datastore = /** @class */ (function () {\n function Datastore(databaseInfo, queue, connection, credentials, serializer, initialBackoffDelay) {\n this.databaseInfo = databaseInfo;\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n this.initialBackoffDelay = initialBackoffDelay;\n }\n Datastore.prototype.newPersistentWriteStream = function (listener) {\n return new PersistentWriteStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, listener, this.initialBackoffDelay);\n };\n Datastore.prototype.newPersistentWatchStream = function (listener) {\n return new PersistentListenStream(this.databaseInfo, this.queue, this.connection, this.credentials, this.serializer, listener, this.initialBackoffDelay);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeRPC('batchGet', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invoke(rpcName, request, token);\n });\n };\n return Datastore;\n}());\nexport { Datastore };\n\n//# sourceMappingURL=datastore.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/datastore.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from './snapshot_version';\nimport { documentVersionMap } from '../model/collections';\nimport { NoDocument } from '../model/document';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { Code, FirestoreError } from '../util/error';\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.equals(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\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 */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return Precondition.updateTime(version);\n }\n else {\n return Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.equals(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\nexport { Transaction };\n\n//# sourceMappingURL=transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/transaction.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Transaction } from '../core/transaction';\nimport { OnlineState } from '../core/types';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatchResult } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { ResetMapping, UpdateMapping } from './remote_event';\nimport { isPermanentError } from './rpc_error';\nimport { WatchChangeAggregator, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nvar LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n// The RemoteStore notifies an onlineStateHandler with OnlineState.Failed if we\n// fail to connect to the backend. This subsequently triggers get() requests to\n// fail or use cached data, etc. Unfortunately, our connections have\n// historically been subject to various transient failures. So we wait for\n// multiple failures before notifying the onlineStateHandler.\nvar ONLINE_ATTEMPTS_BEFORE_FAILURE = 2;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar RemoteStore = /** @class */ (function () {\n function RemoteStore(databaseInfo, asyncQueue, \n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, onlineStateHandler) {\n this.databaseInfo = databaseInfo;\n this.asyncQueue = asyncQueue;\n this.localStore = localStore;\n this.datastore = datastore;\n this.onlineStateHandler = onlineStateHandler;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\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.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n /**\n * The online state of the watch stream. The state is set to healthy if and\n * only if there are messages received by the backend.\n */\n this.watchStreamOnlineState = OnlineState.Unknown;\n /** A count of consecutive failures to open the stream. */\n this.watchStreamFailures = 0;\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n RemoteStore.prototype.setOnlineStateToHealthy = function () {\n this.updateAndBroadcastOnlineState(OnlineState.Healthy);\n };\n RemoteStore.prototype.setOnlineStateToUnknown = function () {\n // The state is set to unknown when a healthy stream is closed (e.g. due to\n // a token timeout) or when we have no active listens and therefore there's\n // no need to start the stream. Assuming there is (possibly in the future)\n // an active listen, then we will eventually move to state Online or Failed,\n // but we always want to make at least ONLINE_ATTEMPTS_BEFORE_FAILURE\n // attempts before failing, so we reset the count here.\n this.watchStreamFailures = 0;\n this.updateAndBroadcastOnlineState(OnlineState.Unknown);\n };\n RemoteStore.prototype.updateOnlineStateAfterFailure = function () {\n // The first failure after we are successfully connected moves us to the\n // 'Unknown' state. We then may make multiple attempts (based on\n // ONLINE_ATTEMPTS_BEFORE_FAILURE) before we actually report failure.\n if (this.watchStreamOnlineState === OnlineState.Healthy) {\n this.setOnlineStateToUnknown();\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= ONLINE_ATTEMPTS_BEFORE_FAILURE) {\n this.updateAndBroadcastOnlineState(OnlineState.Failed);\n }\n }\n };\n RemoteStore.prototype.updateAndBroadcastOnlineState = function (onlineState) {\n var didChange = this.watchStreamOnlineState !== onlineState;\n this.watchStreamOnlineState = onlineState;\n if (didChange) {\n this.onlineStateHandler(onlineState);\n }\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) == (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Only to be called as the counterpart to disableNetwork(). */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n assert(this.watchStream == null, 'enableNetwork() called with non-null watchStream.');\n assert(this.writeStream == null, 'enableNetwork() called with non-null writeStream.');\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n this.writeStream = this.datastore.newPersistentWriteStream({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n _this.updateAndBroadcastOnlineState(OnlineState.Unknown);\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /** Temporarily disables the network. The network can be re-enabled using enableNetwork(). */\n RemoteStore.prototype.disableNetwork = function () {\n this.updateAndBroadcastOnlineState(OnlineState.Failed);\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n return Promise.resolve();\n };\n RemoteStore.prototype.shutdown = function () {\n log.debug(LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetwork();\n return Promise.resolve(undefined);\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!objUtils.contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(objUtils.contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n var queryData = this.listenTargets[targetId];\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\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 */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\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 */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start();\n };\n /**\n * Returns whether the watch stream should be started because there are\n * active targets trying to be listened too\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !objUtils.isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n var _this = this;\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n objUtils.forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.updateOnlineStateAfterFailure();\n this.startWatchStream();\n }\n else {\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 this.setOnlineStateToUnknown();\n }\n return Promise.resolve();\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n // Mark the connection as healthy because we got a message from the server\n this.setOnlineStateToHealthy();\n if (watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.equals(SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n var changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return this.handleWatchChangeBatch(snapshotVersion, changes);\n }\n else {\n return Promise.resolve();\n }\n };\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 RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n objUtils.forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new DocumentKey(query.path);\n var deletedDoc = new NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () {\n if (objUtils.contains(_this.listenTargets, targetId)) {\n delete _this.listenTargets[targetId];\n return _this.syncEngine.rejectListen(targetId, error);\n }\n else {\n // A watched target might have been removed already.\n return Promise.resolve();\n }\n });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n *\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n var _this = this;\n if (!this.canWriteMutations()) {\n return Promise.resolve();\n }\n else {\n return this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n return Promise.resolve();\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n });\n }\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start();\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n this.writeStream.writeHandshake();\n return Promise.resolve();\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n var _this = this;\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // Ignore close if there are no pending writes.\n if (this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n // A promise that is resolved after we processed the error\n var errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n });\n }\n else {\n // No pending writes, nothing to do\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n log.debug(LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return this.localStore.setLastStreamToken(emptyByteString());\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n var _this = this;\n if (isPermanentError(error.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 var batch = this.pendingWrites.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 this.writeStream.inhibitBackoff();\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n });\n }\n else {\n // Transient error, just let the retry logic kick in.\n return Promise.resolve();\n }\n };\n RemoteStore.prototype.createTransaction = function () {\n return new Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n log.debug(LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetwork();\n return this.enableNetwork();\n };\n return RemoteStore;\n}());\nexport { RemoteStore };\n\n//# sourceMappingURL=remote_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { EventManager, QueryListener } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistence } from '../local/memory_persistence';\nimport { NoOpGarbageCollector } from '../local/no_op_garbage_collector';\nimport { Datastore } from '../remote/datastore';\nimport { RemoteStore } from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code } from '../util/error';\nimport { debug } from '../util/log';\nimport { Deferred } from '../util/promise';\nvar LOG_TAG = 'FirestoreClient';\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 */\nvar FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \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 asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.schedule(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.schedule(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new NoOpGarbageCollector();\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new EagerGarbageCollector();\n this.persistence = new MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new Datastore(_this.databaseInfo, _this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.eventMgr.onOnlineStateChanged(onlineState);\n };\n _this.remoteStore = new RemoteStore(_this.databaseInfo, _this.asyncQueue, _this.localStore, datastore, onlineStateChangedHandler);\n _this.syncEngine = new SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.schedule(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .schedule(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new QueryListener(query, observer, options);\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.schedule(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.schedule(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .schedule(function () {\n return Promise.resolve();\n })\n .then(function () {\n return _this.syncEngine.runTransaction(updateFunction);\n });\n };\n return FirestoreClient;\n}());\nexport { FirestoreClient };\n\n//# sourceMappingURL=firestore_client.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/firestore_client.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 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 */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\nexport { AsyncObserver };\n\n//# sourceMappingURL=async_observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert, fail } from './assert';\nimport * as log from './log';\nimport { Deferred } from './promise';\nvar AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // The number of ops that are queued to be run in the future (i.e. they had a\n // delay that has not yet elapsed).\n this.delayedOpCount = 0;\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n *\n * Can optionally specify a delay to wait before queuing the operation.\n */\n AsyncQueue.prototype.schedule = function (op, delay) {\n var _this = this;\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + this.failure.message);\n }\n if ((delay || 0) > 0) {\n this.delayedOpCount++;\n var deferred_1 = new Deferred();\n setTimeout(function () {\n _this.scheduleInternal(function () {\n return op().then(function (result) {\n deferred_1.resolve(result);\n });\n });\n _this.delayedOpCount--; // decrement once it's actually queued.\n }, delay);\n return deferred_1.promise;\n }\n else {\n return this.scheduleInternal(op);\n }\n };\n AsyncQueue.prototype.scheduleInternal = function (op) {\n var _this = this;\n this.tail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n log.error('INTERNAL UNHANDLED ERROR: ', error.stack || error.message);\n throw error;\n })\n .then(function () {\n _this.operationInProgress = false;\n });\n });\n return this.tail;\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n AsyncQueue.prototype.drain = function () {\n // TODO(mikelehen): This should perhaps also drain items that are queued to\n // run in the future (perhaps by artificially running them early), but since\n // no tests need that yet, I didn't bother for now.\n assert(this.delayedOpCount === 0, \"draining doesn't handle delayed ops.\");\n return this.schedule(function () { return Promise.resolve(undefined); });\n };\n return AsyncQueue;\n}());\nexport { AsyncQueue };\n\n//# sourceMappingURL=async_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isUnauthenticated = function () {\n return this.uid == null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isUnauthenticated()) {\n return 'anonymous-user';\n }\n else {\n return 'uid:' + this.uid;\n }\n };\n User.prototype.equals = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\nexport { User };\n\n//# sourceMappingURL=user.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/auth/user.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { makeConstructorPrivate } from '../util/api';\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n return FieldValueImpl;\n}());\nexport { FieldValueImpl };\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\n __extends(DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\nexport { DeleteFieldValueImpl };\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n __extends(ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\nexport { ServerTimestampFieldValueImpl };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nexport var PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_value.js\n// module id = null\n// module chunks = ","(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function p(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var q=\"closure_uid_\"+(1E9*Math.random()>>>0),ea=0;function fa(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ha(a,b,c){if(!a)throw Error();if(2b?1:0};function na(a,b){b.unshift(a);ja.call(this,ka.apply(null,b));b.shift()}u(na,ja);na.prototype.name=\"AssertionError\";function oa(a,b){throw new na(\"Failure\"+(a?\": \"+a:\"\"),Array.prototype.slice.call(arguments,1));};function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this);this.i=this.i;this.v=this.v}var qa=0,ra={};w.prototype.i=!1;w.prototype.Y=function(){if(!this.i&&(this.i=!0,this.w(),0!=qa)){var a=this[q]||(this[q]=++ea);delete ra[a]}};w.prototype.w=function(){if(this.v)for(;this.v.length;)this.v.shift()()};var sa=Array.prototype.indexOf?function(a,b,c){return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(l(a))return l(b)&&1==b.length?a.indexOf(b,c):-1;for(;cb?null:l(a)?a.charAt(b):a[b]}function wa(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function xa(a){return Array.prototype.concat.apply([],arguments)}function ya(a){var b=a.length;if(0parseFloat(Qa)){Pa=String(Ta);break a}}Pa=Qa}var Ja={};\nfunction Ua(a){return Ia(a,function(){for(var b=0,c=la(String(Pa)).split(\".\"),d=la(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var cb=\"closure_listenable_\"+(1E6*Math.random()|0);function db(a){return!(!a||!a[cb])}var eb=0;function fb(a,b,c,d,e){this.listener=a;this.a=null;this.src=b;this.type=c;this.capture=!!d;this.da=e;this.key=++eb;this.X=this.ba=!1}function gb(a){a.X=!0;a.listener=null;a.a=null;a.src=null;a.da=null};function hb(a){this.src=a;this.a={};this.b=0}hb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=ib(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=yb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function qb(a){if(da(a))return a;a[Ab]||(a[Ab]=function(b){return a.handleEvent(b)});return a[Ab]};function B(){w.call(this);this.c=new hb(this);this.P=this;this.J=null}u(B,w);B.prototype[cb]=!0;g=B.prototype;g.addEventListener=function(a,b,c,d){ob(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){wb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.J;if(c)for(b=[];c;c=c.J)b.push(c);c=this.P;var d=a.type||a;if(l(a))a=new A(a,c);else if(a instanceof A)a.target=a.target||c;else{var e=a;a=new A(d,c);Ga(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Bb(h,d,!0,a)&&e}h=a.a=c;e=Bb(h,d,!0,a)&&e;e=Bb(h,d,!1,a)&&e;if(b)for(f=0;f=lc(this).value)for(da(b)&&(b=b()),a=new dc(a,String(b),this.f),c&&(a.a=c),c=\"log:\"+a.b,(a=k.console)&&a.timeStamp&&a.timeStamp(c),(a=k.msWriteProfilerMark)&&a(c),c=this;c;)c=c.a};function F(a,b){a.log(gc,b,void 0)}function G(a,b){a.log(hc,b,void 0)}var mc={},nc=null;\nfunction oc(a){nc||(nc=new fc(\"\"),mc[\"\"]=nc,nc.c=jc);var b;if(!(b=mc[a])){b=new fc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=oc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;mc[a]=b}return b};function pc(a,b){a&&a.log(ic,b,void 0)}function H(a,b){a&&a.log(kc,b,void 0)};function qc(){this.a=oc(\"goog.labs.net.webChannel.WebChannelDebug\")}function rc(a,b,c,d){if(c)try{var e=JSON.parse(c);if(e)for(var f=0;fh.length)){var m=h[1];if(n(m)&&!(1>m.length)){var v=m[0];if(\"noop\"!=v&&\"stop\"!=v&&\"close\"!=v)for(var Sa=1;Sab||3==b&&!Ka&&!this.a.U())){this.s||4!=b||7==c||uc();Rc(this);var d=this.a.V();this.v=d;var e=this.a.U();e||I(this.b,\"No response text for uri \"+this.g+\" status \"+d);this.c=200==d;I(this.b,\"XMLHTTP RESP (\"+this.f+\") [ attempt \"+this.S+\"]: \"+this.j+\"\\n\"+this.g+\"\\n\"+b+\" \"+d);if(this.c)this.J?(Sc(this,b,e),Ka&&this.c&&3==b&&(this.M.$(this.F,\"tick\",this.fb),this.F.start())):(rc(this.b,this.f,e,null),Tc(this,e)),4==b&&Uc(this),this.c&&\n!this.s&&(4==b?this.m.wa(this):(this.c=!1,Pc(this)));else{if(400==d&&0b.length)return Kc;b=b.substr(d,c);a.C=d+c;return b}g.cancel=function(){this.s=!0;Uc(this)};function Pc(a){a.T=t()+a.P;Xc(a,a.P)}function Xc(a,b){if(null!=a.o)throw Error(\"WatchDog timer not null\");a.o=xc(r(a.eb,a),b)}function Rc(a){a.o&&(k.clearTimeout(a.o),a.o=null)}\ng.eb=function(){this.o=null;var a=t();if(0<=a-this.T)this.c&&(a=this.b.a)&&F(a,\"Received watchdog timeout even though request loaded successfully\"),I(this.b,\"TIMEOUT: \"+this.g),2!=this.I&&(uc(),K()),Uc(this),this.i=2,Vc(this);else{var b=this.b.a;b&&G(b,\"WatchDog timer called too early\");Xc(this,this.T-a)}};function Vc(a){a.m.Ka()||a.s||a.m.wa(a)}function Uc(a){Rc(a);var b=a.G;b&&\"function\"==typeof b.Y&&b.Y();a.G=null;Yb(a.F);cc(a.M);a.a&&(b=a.a,a.a=null,b.abort(),b.Y())}\nfunction Tc(a,b){try{a.m.Na(a,b),uc()}catch(c){sc(a.b,c,\"Error in httprequest callback\")}};function Yc(a){if(a.A&&\"function\"==typeof a.A)return a.A();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&$c(a),!0):!1}function $c(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function hd(a,b,c){b instanceof kd?(a.c=b,qd(a.c,a.h)):(c||(b=ld(b,rd)),a.c=new kd(b,0,a.h))}\nfunction R(a,b,c){a.c.set(b,c)}function Qc(a,b,c){n(c)||(c=[String(c)]);sd(a.c,b,c)}function Mc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36));return a}function td(a){return a instanceof Q?M(a):new Q(a,void 0)}function ud(a,b,c,d){var e=new Q(null,void 0);a&&ed(e,a);b&&fd(e,b);c&&gd(e,c);d&&(e.a=d);return e}function jd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction ld(a,b,c){return l(a)?(a=encodeURI(a).replace(b,vd),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function vd(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var md=/[#\\/\\?@]/g,od=/[#\\?:]/g,nd=/[#\\?]/g,rd=/[#\\?@]/g,pd=/#/g;function kd(a,b,c){this.b=this.a=null;this.c=a||null;this.f=!!c}function S(a){a.a||(a.a=new O,a.b=0,a.c&&dd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=kd.prototype;g.u=function(){S(this);return this.b};\ng.add=function(a,b){S(this);this.c=null;a=wd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function xd(a,b){S(a);b=wd(a,b);P(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,bd(a.a,b))}function yd(a,b){S(a);b=wd(a,b);return P(a.a.b,b)}g.forEach=function(a,b){S(this);this.a.forEach(function(c,d){ta(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.O=function(){S(this);for(var a=this.a.A(),b=this.a.O(),c=[],d=0;d=a.c:!1}function Td(a,b){return a.b?a.b==b:a.a?a.a.contains(b):!1}function Rd(a,b){a.a?a.a.add(b):a.b=b}\nOd.prototype.cancel=function(){this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ta(this.a.A(),function(a){a.cancel()}),ad(this.a.a))};function Ud(a,b){this.a=a;this.b=b};function Vd(a,b){this.a=a;this.b=b}Vd.prototype.stringify=function(a){return k.JSON.stringify(a,this.a)};Vd.prototype.parse=function(a){return k.JSON.parse(a,this.b)};function Wd(){this.a=new Vd}function Xd(a,b,c){var d=c||\"\";try{Zc(a,function(a,c){var e=a;p(a)&&(e=Eb(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function Yd(a,b){var c=new qc;I(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ia(Zd,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ia(Zd,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ia(Zd,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ia(Zd,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function Zd(a,b,c,d,e){try{I(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){sc(a,f)}};function U(a){B.call(this);this.headers=new O;this.G=a||null;this.f=!1;this.F=this.a=null;this.M=this.s=\"\";this.j=0;this.g=\"\";this.h=this.I=this.o=this.H=!1;this.l=0;this.B=null;this.N=$d;this.C=this.m=!1}u(U,B);var $d=\"\";U.prototype.b=oc(\"goog.net.XhrIo\");var ae=/^https?$/i,be=[\"POST\",\"PUT\"];g=U.prototype;\ng.ta=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.s+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.s=a;this.g=\"\";this.j=0;this.M=b;this.H=!1;this.f=!0;this.a=this.G?Fc(this.G):Fc(Dc);this.F=this.G?Bc(this.G):Bc(Dc);this.a.onreadystatechange=r(this.Ma,this);try{H(this.b,V(this,\"Opening Xhr\")),this.I=!0,this.a.open(b,String(a),!0),this.I=!1}catch(f){H(this.b,V(this,\"Error opening Xhr: \"+f.message));ce(this,f);return}a=c||\"\";var e=new O(this.headers);\nd&&Zc(d,function(a,b){e.set(b,a)});d=ua(e.O());c=k.FormData&&a instanceof k.FormData;!(0<=sa(be,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.N&&(this.a.responseType=this.N);\"withCredentials\"in this.a&&this.a.withCredentials!==this.m&&(this.a.withCredentials=this.m);try{de(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}R(a,b,c);return a};function ke(a,b,c){this.za=b||0;this.Ba=0;this.h=[];this.l=[];this.a=new qc;this.J=c||new Md;this.ia=this.ya=this.H=this.ja=this.b=this.N=this.j=this.ha=this.f=this.P=this.i=null;this.Va=this.I=0;this.ka=this.C=this.s=this.m=this.o=this.c=null;this.v=this.Aa=this.S=-1;this.ga=this.B=this.G=0;this.T=a&&a.supportsCrossDomainXhr||!1;this.M=\"\";this.g=new Od(a&&a.concurrentRequestLimit);this.la=new Wd;this.F=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;this.Ua=a&&a.fastHandshake||!1}\ng=ke.prototype;g.oa=8;g.D=1;function le(a){I(a.a,\"disconnect()\");me(a);if(3==a.D){var b=a.I++,c=M(a.H);R(c,\"SID\",a.M);R(c,\"RID\",b);R(c,\"TYPE\",\"terminate\");ne(a,c);b=new L(a,a.a,0,b,void 0);b.I=2;b.l=Mc(M(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.l.toString(),\"\"));c||((new Image).src=b.l);b.H=t();Pc(b)}oe(a)}\nfunction me(a){a.C&&(a.C.abort(),a.C=null);a.b&&(a.b.cancel(),a.b=null);a.m&&(k.clearTimeout(a.m),a.m=null);pe(a);a.g.cancel();a.o&&(k.clearTimeout(a.o),a.o=null)}function qe(a,b){if(1E3==a.h.length){var c=\"Already have 1000 queued maps upon queueing \"+Eb(b),d=a.a.a;d&&F(d,c)}a.h.push(new Ud(a.Va++,b));3==a.D&&re(a)}g.Ka=function(){return 0==this.D};function re(a){Sd(a.g)||a.o||(a.o=xc(r(a.Pa,a),0),a.G=0)}\ng.Pa=function(a){this.o=null;I(this.a,\"startForwardChannel_\");if(1==this.D)if(a)(a=this.a.a)&&F(a,\"Not supposed to retry the open\");else{I(this.a,\"open_()\");this.I=Math.floor(1E5*Math.random());a=this.I++;var b=new L(this,this.a,0,a,void 0),c=this.i;this.P&&(c?(c=Ea(c),Ga(c,this.P)):c=this.P);null===this.f&&(b.h=c);var d=se(this),e=M(this.H);R(e,\"RID\",a);0b&&this.ka&&0==this.B&&!this.s&&(this.s=xc(r(this.ab,this),6E3)));else I(this.a,\"Bad POST response data returned\"),W(this,11)}else if(this.b==a&&pe(this),!/^[\\s\\xa0]*$/.test(b))for(b=c=this.la.a.parse(b),c=0;cthis.c)throw Error(Je);this.a=new Ge;this.b=new T;this.g=null;this.aa()}u(Ie,w);var Je=\"[goog.structs.Pool] Min can not be greater than max\";g=Ie.prototype;g.ca=function(){var a=t();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.u()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}Me.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)wa(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.ma=function(a){Y.L.ma.call(this,a);this.ua()};g.aa=function(){Y.L.aa.call(this);this.ua()};g.w=function(){Y.L.w.call(this);k.clearTimeout(void 0);wa(this.f.a);this.f=null};function Z(a,b,c,d){this.l=a;this.j=!!d;Y.call(this,b,c)}u(Z,Y);Z.prototype.qa=function(){var a=new U,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.m=!0);return a};Z.prototype.va=function(a){return!a.i&&!a.a};Be.prototype.createWebChannel=Be.prototype.a;X.prototype.send=X.prototype.l;X.prototype.open=X.prototype.j;X.prototype.close=X.prototype.close;yc.NO_ERROR=0;yc.TIMEOUT=8;yc.HTTP_ERROR=6;zc.COMPLETE=\"complete\";Dd.EventType=Ed;Ed.OPEN=\"a\";Ed.CLOSE=\"b\";Ed.ERROR=\"c\";Ed.MESSAGE=\"d\";B.prototype.listen=B.prototype.$;Z.prototype.getObject=Z.prototype.ca;Z.prototype.releaseObject=Z.prototype.hb;U.prototype.listenOnce=U.prototype.Ia;U.prototype.getLastError=U.prototype.$a;U.prototype.getLastErrorCode=U.prototype.Ga;\nU.prototype.getStatus=U.prototype.V;U.prototype.getStatusText=U.prototype.Ha;U.prototype.getResponseJson=U.prototype.Za;U.prototype.getResponseText=U.prototype.U;U.prototype.getResponseText=U.prototype.U;U.prototype.send=U.prototype.ta;module.exports={createWebChannelTransport:Fe,ErrorCode:yc,EventType:zc,WebChannel:Dd,XhrIoPool:Z};}).call(typeof window !== 'undefined' ? window : this)\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../webchannel-wrapper/dist/index.js\n// module id = 115\n// module chunks = 1"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///firebase-firestore.js","webpack:///./firestore/index.js","webpack:///../firestore/dist/esm/src/util/log.js","webpack:///../firestore/dist/esm/src/util/assert.js","webpack:///../firestore/dist/esm/src/platform/platform.js","webpack:///../firestore/dist/esm/src/util/api.js","webpack:///../firestore/dist/esm/src/util/obj.js","webpack:///../firestore/dist/esm/src/util/input_validation.js","webpack:///../firestore/dist/esm/src/util/misc.js","webpack:///../firestore/dist/esm/src/api/blob.js","webpack:///../firestore/dist/esm/src/model/field_value.js","webpack:///../firestore/dist/esm/src/util/types.js","webpack:///../firestore/dist/esm/src/core/query.js","webpack:///../firestore/dist/esm/src/remote/rpc_error.js","webpack:///../firestore/dist/esm/src/model/collections.js","webpack:///../firestore/dist/esm/src/remote/watch_change.js","webpack:///../firestore/dist/esm/src/remote/serializer.js","webpack:///../firestore/dist/esm/src/api/field_path.js","webpack:///../firestore/dist/esm/src/core/view.js","webpack:///../firestore/dist/esm/src/local/encoded_resource_path.js","webpack:///../firestore/dist/esm/src/local/indexeddb_schema.js","webpack:///../firestore/dist/esm/src/local/simple_db.js","webpack:///../firestore/dist/esm/src/local/indexeddb_mutation_queue.js","webpack:///../firestore/dist/esm/src/local/indexeddb_query_cache.js","webpack:///../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js","webpack:///../firestore/dist/esm/src/local/local_serializer.js","webpack:///../firestore/dist/esm/src/api/credentials.js","webpack:///../firestore/dist/esm/src/api/observer.js","webpack:///../firestore/dist/esm/src/api/user_data_converter.js","webpack:///../firestore/dist/esm/src/api/database.js","webpack:///../firestore/dist/esm/src/platform/config.js","webpack:///../firestore/dist/esm/index.js","webpack:///../firestore/dist/esm/src/core/version.js","webpack:///../firestore/dist/esm/src/util/error.js","webpack:///../firestore/dist/esm/src/api/geo_point.js","webpack:///../firestore/dist/esm/src/core/database_info.js","webpack:///../firestore/dist/esm/src/model/path.js","webpack:///../firestore/dist/esm/src/model/document_key.js","webpack:///../firestore/dist/esm/src/model/document.js","webpack:///../firestore/dist/esm/src/util/sorted_map.js","webpack:///../firestore/dist/esm/src/local/query_data.js","webpack:///../firestore/dist/esm/src/core/timestamp.js","webpack:///../firestore/dist/esm/src/core/snapshot_version.js","webpack:///../firestore/dist/esm/src/model/mutation.js","webpack:///../firestore/dist/esm/src/remote/existence_filter.js","webpack:///../firestore/dist/esm/src/util/sorted_set.js","webpack:///../firestore/dist/esm/src/remote/remote_event.js","webpack:///../firestore/dist/esm/src/remote/stream_bridge.js","webpack:///../firestore/dist/esm/src/platform_browser/webchannel_connection.js","webpack:///../firestore/dist/esm/src/platform_browser/browser_platform.js","webpack:///../firestore/dist/esm/src/platform_browser/browser_init.js","webpack:///../firestore/dist/esm/src/core/types.js","webpack:///../firestore/dist/esm/src/core/view_snapshot.js","webpack:///../firestore/dist/esm/src/core/target_id_generator.js","webpack:///../firestore/dist/esm/src/model/document_set.js","webpack:///../firestore/dist/esm/src/util/obj_map.js","webpack:///../firestore/dist/esm/src/core/event_manager.js","webpack:///../firestore/dist/esm/src/local/persistence_promise.js","webpack:///../firestore/dist/esm/src/local/eager_garbage_collector.js","webpack:///../firestore/dist/esm/src/local/local_view_changes.js","webpack:///../firestore/dist/esm/src/local/reference_set.js","webpack:///../firestore/dist/esm/src/util/async_queue.js","webpack:///../firestore/dist/esm/src/core/sync_engine.js","webpack:///../firestore/dist/esm/src/model/mutation_batch.js","webpack:///../firestore/dist/esm/src/local/indexeddb_persistence.js","webpack:///../firestore/dist/esm/src/local/local_documents_view.js","webpack:///../firestore/dist/esm/src/local/remote_document_change_buffer.js","webpack:///../firestore/dist/esm/src/local/local_store.js","webpack:///../firestore/dist/esm/src/local/memory_mutation_queue.js","webpack:///../firestore/dist/esm/src/local/memory_query_cache.js","webpack:///../firestore/dist/esm/src/local/memory_remote_document_cache.js","webpack:///../firestore/dist/esm/src/local/memory_persistence.js","webpack:///../firestore/dist/esm/src/local/no_op_garbage_collector.js","webpack:///../firestore/dist/esm/src/util/promise.js","webpack:///../firestore/dist/esm/src/remote/persistent_stream.js","webpack:///../firestore/dist/esm/src/remote/backoff.js","webpack:///../firestore/dist/esm/src/remote/datastore.js","webpack:///../firestore/dist/esm/src/core/transaction.js","webpack:///../firestore/dist/esm/src/remote/online_state_tracker.js","webpack:///../firestore/dist/esm/src/remote/remote_store.js","webpack:///../firestore/dist/esm/src/core/firestore_client.js","webpack:///../firestore/dist/esm/src/util/async_observer.js","webpack:///../firestore/dist/esm/src/auth/user.js","webpack:///../firestore/dist/esm/src/api/field_value.js","webpack:///../webchannel-wrapper/dist/index.js","webpack:///../logger/dist/esm/index.js","webpack:///../logger/dist/esm/src/logger.js"],"names":["webpackJsonpFirebase","115","module","exports","__webpack_require__","116","__webpack_exports__","getLogLevel","logClient","logLevel","dist_esm","DEBUG","LogLevel","SILENT","ERROR","setLogLevel","newLevel","error","SDK_VERSION","debug","tag","msg","obj","_i","arguments","length","args","map","argToString","apply","concat","log_error","platform","platform_PlatformSupport","getPlatform","formatJSON","e","fail","failure","message","Error","assert","assertion","emptyByteString","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","error_FirestoreError","Code","INVALID_ARGUMENT","prototype","staticProperty","hasOwnProperty","contains","key","Object","call","defaulted","value","defaultValue","undefined","forEachNumber","fn","num","isNaN","forEach","isEmpty","shallowCopy","result","validateExactNumberOfArgs","functionName","numberOfArgs","formatPlural","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateNamedArrayAtLeastNumberOfElements","name","minNumberOfElements","Array","validateArgType","type","position","argument","validateType","ordinal","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateNamedPropertyEquals","inputName","input","expected","expectedDescription","expected_1","val","push","valueDescription","actualDescription","join","validateNamedOptionalPropertyEquals","isPlainObject","description","getPrototypeOf","substring","JSON","stringify","customObjectName","tryGetCustomObjectType","constructor","funcNameRegex","results","exec","validateDefined","validateOptionNames","options","optionNames","_","indexOf","invalidClassError","str","primitiveComparator","left","right","equals","isEqual","arrayEquals","i","immediatePredecessor","s","lastIndex","charAt","String","fromCharCode","charCodeAt","immediateSuccessor","assertUint8ArrayAvailable","Uint8Array","UNIMPLEMENTED","assertBase64Available","base64Available","numericComparator","numericEquals","isNullOrUndefined","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","fieldFilter","field","op","field_value_NullValue","INSTANCE","query_RelationOp","EQUAL","NullFilter","field_value_DoubleValue","NAN","NanFilter","query_RelationFilter","isPermanentError","code","OK","CANCELLED","UNKNOWN","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","INTERNAL","UNAVAILABLE","UNAUTHENTICATED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","DATA_LOSS","mapCodeFromRpcStatus","status","RpcCode","mapCodeFromRpcCode","mapRpcCodeFromCode","mapCodeFromHttpStatus","maybeDocumentMap","EMPTY_MAYBE_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_MAP","documentVersionMap","EMPTY_DOCUMENT_VERSION_MAP","documentKeySet","EMPTY_DOCUMENT_KEY_SET","applyResumeToken","change","resumeToken","assertPresent","parseInt64","hasTag","fromDotSeparatedString","path","search","RESERVED","field_path_FieldPath","bind","split","compareChangeType","c1","c2","order","ChangeType","Added","Modified","Metadata","Removed","encode","encodeSeparator","encodeSegment","get","segment","resultBuf","c","escapeChar","encodedNul","encodedEscape","encodedSeparatorChar","decode","path_ResourcePath","EMPTY_PATH","lastReasonableEscapeIndex","segments","segmentBuilder","start","end","currentPiece","createOrUpgradeDb","db","txn","fromVersion","toVersion","createOwnerStore","createMutationQueue","createQueryCache","createRemoteDocumentCache","p","persistence_promise_PersistencePromise","resolve","ensureTargetGlobalExists","next","targetGlobal","saveTargetCount","createObjectStore","DbOwner","store","DbMutationQueue","keyPath","DbMutationBatch","indexeddb_schema_DbDocumentMutation","DbRemoteDocument","DbTargetDocument","createIndex","documentTargetsIndex","documentTargetsKeyPath","unique","DbTarget","queryTargetsIndexName","queryTargetsKeyPath","DbTargetGlobal","metadata","globalStore","count","targetCount","put","snapshot_version_SnapshotVersion","MIN","toTimestamp","wrapRequest","request","reject","onsuccess","event","target","onerror","validateStreamToken","token","mutationsStore","getStore","documentMutationsStore","mutationQueuesStore","simple_db_SimpleDbTransaction","targetsStore","indexeddb_query_cache_getStore","globalTargetStore","documentTargetStore","remoteDocumentsStore","dbKey","docKey","toArray","isDocumentQuery","dbQuery","documents","makeCredentialsProvider","credentials","credentials_EmptyCredentialsProvider","credentials_FirstPartyCredentialsProvider","client","sessionIndex","isPartialObserver","implementsAnyMethods","methods","object","methods_1","method","isWrite","dataSource","UserDataSource","Set","MergeSet","Update","QueryValue","looksLikeJsonObject","Date","geo_point_GeoPoint","blob_Blob","DocumentKeyReference","FieldValueImpl","validatePlainObject","context","createError","fieldPathFromArgument","methodName","_internalPath","fieldPathFromDotSeparatedString","errorMessage","validateSetOptions","merge","validateSnapshotOptions","serverTimestamps","validateReference","documentRef","firestore","database_DocumentReference","changesFromSnapshot","snapshot","oldDocs","lastDoc_1","index_1","docChanges","doc","database_QueryDocumentSnapshot","fromCache","query","docComparator","oldIndex","newIndex","indexTracker_1","delete","add","resultChangeType","configureForFirebase","firebase","registerService","app","database_Firestore","firestoreNamespace","registerFirestore","instance","defineProperty","esm","PlatformSupport","setPlatform","tslib_es6","_super","FirestoreError","_this","this","toString","misc_AutoId","AutoId","newId","chars","autoId","Math","floor","random","Blob","binaryString","_binaryString","fromBase64String","base64","atob","fromUint8Array","array","char","toBase64","btoa","toUint8Array","buffer","other","_compareTo","PublicBlob","GeoPoint","latitude","longitude","isFinite","_lat","_long","enumerable","configurable","DatabaseInfo","databaseId","persistenceKey","host","ssl","DEFAULT_DATABASE_NAME","database_info_DatabaseId","DatabaseId","projectId","database","compareTo","path_Path","Path","offset","init","len","construct","create","comparator","child","nameOrPath","slice","limit","popFirst","size","popLast","firstSegment","lastSegment","index","isPrefixOf","p1","p2","min","ResourcePath","canonicalString","fromString","filter","identifierRegExp","path_FieldPath","FieldPath","isValidIdentifier","test","replace","isKeyField","keyField","fromServerFormat","current","addCurrentSegment","inBackticks","document_key_DocumentKey","DocumentKey","isDocumentKey","k1","k2","fromSegments","fromPathString","EMPTY","document_Document","Document","version","data","hasLocalMutations","fieldValue","compareByKey","d1","d2","compareByField","v1","v2","document_NoDocument","NoDocument","SortedMap","root","sorted_map_LLRBNode","insert","copy","BLACK","remove","node","cmp","prunedNodes","minKey","maxKey","inorderTraversal","action","k","v","reverseTraversal","getIterator","sorted_map_SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","SortedMapIterator","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","LLRBNode","color","RED","n","fixUp","removeMin","isRed","moveRedLeft","smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","nl","nr","checkMaxDepth","blackDepth","check","pow","LLRBEmptyNode","TypeOrder","ServerTimestampBehavior","QueryPurpose","field_value_FieldValueOptions","FieldValueOptions","serverTimestampBehavior","fromSnapshotOptions","Estimate","Previous","defaultOptions","Default","field_value_FieldValue","FieldValue","defaultCompareTo","typeOrder","NullValue","internalValue","field_value_BooleanValue","BooleanValue","of","TRUE","FALSE","field_value_NumberValue","NumberValue","field_value_IntegerValue","IntegerValue","DoubleValue","NaN","POSITIVE_INFINITY","Infinity","NEGATIVE_INFINITY","field_value_StringValue","StringValue","field_value_TimestampValue","TimestampValue","toDate","field_value_ServerTimestampValue","ServerTimestampValue","localWriteTime","previousValue","field_value_BlobValue","BlobValue","field_value_RefValue","RefValue","field_value_GeoPointValue","GeoPointValue","field_value_ObjectValue","ObjectValue","it1","it2","next1","next2","set","to","setChild","newChild","pathSegment","childName","field_value_ArrayValue","ArrayValue","minLength","NumberAsAny","Number","query_Query","Query","explicitOrderBy","filters","startAt","endAt","memoizedCanonicalId","memoizedOrderBy","assertValidBound","atPath","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","KEY_ORDERING_ASC","query_OrderBy","foundKeyOrdering","_a","orderBy","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","addFilter","isInequality","newFilters","addOrderBy","newOrderBy","withLimit","withStartAt","bound","withEndAt","canonicalId","_b","_c","comparedOnKeyField","comp","compare","matches","matchesAncestor","matchesOrderBy","matchesFilters","matchesBounds","hasLimit","docPath","sortsBeforeDocument","RelationOp","LESS_THAN","LESS_THAN_OR_EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","RelationFilter","refValue","comparison","matchesComparison","matchesValue","DESCENDING","query_Bound","Bound","before","component","orderByComponent","docValue","thisPosition","otherPosition","OrderBy","isKeyOrderBy","isoRegExp","RegExp","timestamp_Timestamp","Timestamp","seconds","nanos","now","fromEpochMilliseconds","fromDate","date","getTime","milliseconds","fromISOString","utc","fraction","nanoStr","substr","toEpochMilliseconds","SnapshotVersion","timestamp","fromMicroseconds","fromTimestamp","forDeletedDoc","toMicroseconds","MutationType","query_data_QueryData","QueryData","targetId","purpose","snapshotVersion","update","updated","mutation_FieldMask","FieldMask","fields","ServerTimestampTransform","FieldTransform","transform","MutationResult","transformResults","mutation_Precondition","Precondition","updateTime","exists","isValidFor","maybeDoc","isNone","NONE","mutation_Mutation","Mutation","verifyKeyMatches","getPostMutationVersion","mutation_SetMutation","SetMutation","precondition","applyToRemoteDocument","mutationResult","applyToLocalView","baseDoc","mutation_PatchMutation","PatchMutation","fieldMask","Patch","newData","patchDocument","patchObject","fieldPath","newValue","mutation_TransformMutation","TransformMutation","fieldTransforms","Transform","requireDocument","transformObject","localTransformResults","fieldTransform","mutation_DeleteMutation","DeleteMutation","Delete","ExistenceFilter","CurrentStatusUpdate","sorted_set_SortedSet","SortedSet","fromMapKeys","keys","has","elem","first","last","cb","forEachInRange","range","iter","forEachWhile","firstAfterOrEqual","unionWith","thisIt","otherIt","thisElem","otherElem","remote_event_RemoteEvent","RemoteEvent","targetChanges","documentUpdates","addDocumentUpdate","handleExistenceFilterMismatch","mapping","ResetMapping","currentStatusUpdate","MarkNotCurrent","WatchTargetChangeState","EMPTY_KEY_SET","docs","UpdateMapping","addedDocuments","removedDocuments","applyToKeySet","DocumentWatchChange","updatedTargetIds","removedTargetIds","newDoc","ExistenceFilterChange","existenceFilter","watch_change_WatchTargetChange","WatchTargetChange","state","targetIds","cause","watch_change_WatchChangeAggregator","WatchChangeAggregator","listenTargets","pendingTargetResponses","existenceFilters","frozen","watchChange","addDocumentChange","addTargetChange","addExistenceFilterChange","addChanges","watchChanges","createRemoteEvent","isActiveTarget","ensureTargetChange","None","docChange","relevant","targetChange","NoChange","recordTargetResponse","Current","MarkCurrent","Reset","newCount","DIRECTIONS","dirs","OPERATORS","ops","serializer_JsonProtoSerializer","JsonProtoSerializer","useProto3Json","unsafeCastProtoByteString","byteString","fromRpcStatus","toInt32Value","fromInt32Value","toBytes","bytes","fromBlob","blob","toResourceName","fullyQualifiedPrefixPath","fromResourceName","resource","isValidResourceName","toName","fromName","extractLocalPathFromResourceName","toQueryPath","encodedDatabaseId","fromQueryPath","resourceName","toValue","nullValue","booleanValue","integerValue","doubleValue","stringValue","mapValue","toMapValue","arrayValue","toArrayValue","timestampValue","geoPointValue","bytesValue","referenceValue","fromValue","fromFields","values","dbId","toMutationDocument","toFields","toDocument","document","fromDocument","fromFound","found","fromMissing","missing","readTime","fromMaybeDocument","toWatchTargetChangeState","toTestWatchChange","documentChange","documentDelete","documentRemove","targetChangeType","fromWatchChange","fromWatchTargetChangeState","causeProto","entityChange","docDelete","docRemove","versionFromListenResponse","toMutation","mutation","updateMask","toDocumentMask","toFieldTransform","currentDocument","toPrecondition","fromMutation","proto","fromPrecondition","fromDocumentMask","fromFieldTransform","fromWriteResult","fromWriteResults","protos","setToServerValue","toDocumentsTarget","fromDocumentsTarget","documentsTarget","toQueryTarget","structuredQuery","parent","from","collectionId","where","toFilter","toOrder","toCursor","fromQueryTarget","fromCount","filterBy","fromFilter","fromOrder","fromCursor","toListenRequestLabels","queryData","toLabel","goog-listen-tags","Listen","ExistenceFilterMismatch","LimboResolution","toTarget","toRelationFilter","toUnaryFilter","compositeFilter","unaryFilter","fromUnaryFilter","fromRelationFilter","f","reduce","accum","orderBys","toPropertyOrder","fromPropertyOrder","cursor","toDirection","fromDirection","toOperatorName","fromOperatorName","toFieldPathReference","fromFieldPathReference","fieldReference","direction","nanField","nullField","fieldPaths","paths","dist","stream_bridge_StreamBridge","StreamBridge","sendFn","closeFn","onOpen","callback","wrappedOnOpen","onClose","wrappedOnClose","onMessage","wrappedOnMessage","close","send","callOnOpen","callOnClose","err","callOnMessage","LOG_TAG","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","webchannel_connection_WebChannelConnection","WebChannelConnection","info","pool","baseUrl","modifyHeadersForRequest","headers","header","authHeaders","invokeRPC","rpcName","url","makeUrl","Promise","getObject","xhr","listenOnce","COMPLETE","getLastErrorCode","NO_ERROR","json","getResponseJson","TIMEOUT","HTTP_ERROR","status_1","getStatus","getResponseText","getStatusText","getLastError","releaseObject","requestString","Content-Type","invokeStreamingRPC","openStream","urlParts","webchannelTransport","backgroundChannelTest","httpSessionIdParam","initMessageHeaders","httpHeadersOverwriteParam","messageUrlParams","sendRawJson","supportsCrossDomainXhr","channel","createWebChannel","opened","closed","streamBridge","open","unguardedEventListen","listen","param","setTimeout","EventType","OPEN","CLOSE","MESSAGE","msgData","status_2","urlRpcName","browser_platform_BrowserPlatform","BrowserPlatform","loadConnection","databaseInfo","newSerializer","encoded","raw","OnlineState","fieldNames","documentId","_DOCUMENT_ID","SyncState","GeneratorIds","view_snapshot_DocumentChangeSet","DocumentChangeSet","changeMap","track","oldChange","getChanges","changes","ViewSnapshot","hasPendingWrites","syncStateChanged","otherChanges","document_set_DocumentSet","DocumentSet","keyedMap","sortedSet","emptySet","oldSet","thisDoc","otherDoc","docStrings","newSet","obj_map_ObjectMap","ObjectMap","mapKeyFn","inner","id","matches_1","otherKey","splice","entries","entries_1","QueryListenersInfo","listeners","event_manager_EventManager","EventManager","syncEngine","queries","q","onlineState","Unknown","subscribe","onChange","onError","listener","firstListen","queryInfo","applyOnlineStateChange","viewSnap","onViewSnapshot","then","unlisten","lastListen","viewSnaps","viewSnaps_1","event_manager_QueryListener","QueryListener","queryObserver","raisedInitialEvent","snap","includeDocumentMetadataChanges","shouldRaiseEvent","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","Offline","waitForSyncWhenOnline","hasPendingWritesChanged","includeQueryMetadataChanges","getInitialViewChanges","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","catch","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","promise","nextPromise","idx","initial","eager_garbage_collector_EagerGarbageCollector","EagerGarbageCollector","isEager","sources","potentialGarbage","addGarbageSource","garbageSource","setGarbageCollector","removeGarbageSource","addPotentialGarbageKey","collectGarbage","promises","garbageKeys","hasRefsPromise","documentHasAnyReferences","hasRefs","source","containsKey","local_view_changes_LocalViewChanges","LocalViewChanges","addedKeys","removedKeys","fromSnapshot","viewSnapshot","reference_set_ReferenceSet","ReferenceSet","refsByKey","reference_set_DocReference","refsByTarget","compareByTargetId","garbageCollector","addReference","ref","addReferences","removeReference","removeRef","removeReferences","removeReferencesForId","emptyKey","startRef","endRef","removeAllReferences","referencesForId","firstRef","DocReference","targetOrBatchId","RESERVED_BITS","TimerId","TargetIdGenerator","generatorId","initAfter","afterWithoutGenerator","afterGenerator","previousId","forLocalStore","LocalStore","forSyncEngine","SyncEngine","AddedLimboDocument","RemovedLimboDocument","view_View","View","syncedDocuments","syncState","limboDocuments","mutatedKeys","documentSet","computeDocChanges","previousChanges","changeSet","oldDocumentSet","newMutatedKeys","newDocumentSet","needsRefill","lastDocInLimit","newMaybeDoc","oldDoc","docsEqual","applyChanges","sort","applyTargetChange","limboChanges","updateLimboDocuments","synced","newSyncState","Synced","Local","shouldBeInLimbo","targetMapping","oldLimboDocuments","QueryView","view","sync_engine_SyncEngine","localStore","remoteStore","currentUser","viewHandler","errorHandler","queryViewsByQuery","queryViewsByTarget","limboTargetsByKey","limboKeysByTarget","limboDocumentRefs","limboCollector","mutationUserCallbacks","targetIdGenerator","assertSubscribed","allocateQuery","executeQuery","remoteDocumentKeys","remoteKeys","viewDocChanges","viewChange","queryView","releaseQuery","removeAndCleanupQuery","write","batch","userCallback","localWrite","addMutationCallback","batchId","emitNewSnapsAndNotifyLocalStore","fillWritePipeline","wrapUpdateFunctionError","runTransaction","updateFunction","retries","transaction","createTransaction","userPromise","commit","applyRemoteEvent","remoteEvent","limboKey","newViewSnapshots","rejectListen","docMap","event_1","queryView_1","applySuccessfulWrite","mutationBatchResult","processUserCallback","acknowledgeBatch","rejectFailedWrite","rejectBatch","newCallbacks","toKey","gcLimboDocuments","updateTrackedLimbos","limboChanges_1","limboChange","trackLimboChange","limboTargetId","currentLimboDocs","newSnaps","docChangesInAllViews","queriesProcessed","notifyLocalViewChanges","fnName","handleUserChange","user","BATCHID_UNKNOWN","mutation_batch_MutationBatch","MutationBatch","mutations","batchResult","mutationResults","keySet","isTombstone","toTombstone","mutation_batch_MutationBatchResult","MutationBatchResult","commitVersion","streamToken","docVersions","versionMap","DbTimestamp","ownerId","leaseTimestampMs","userId","lastAcknowledgedBatchId","lastStreamToken","localWriteTimeMs","DbDocumentMutation","prefixForUser","prefixForPath","PLACEHOLDER","DbNoDocument","noDocument","lastListenSequenceNumber","highestTargetId","highestListenSequenceNumber","lastRemoteSnapshotVersion","ALL_STORES","simple_db_SimpleDb","SimpleDb","openOrCreate","runUpgrade","isAvailable","window","indexedDB","onupgradeneeded","oldVersion","deleteDatabase","ua","navigator","userAgent","mode","objectStores","transactionFn","transactionFnResult","abort","completionPromise","IterationController","dbCursor","shouldStop","nextKey","done","skip","SimpleDbTransaction","aborted","onabort","oncomplete","objectStoreNames","storeName","objectStore","simple_db_SimpleDbStore","SimpleDbStore","keyOrValue","loadAll","indexOrRange","iterateCursor","deleteAll","keysOnly","control","iterate","optionsOrCallback","cursorRequest","controller","userResult","primaryKey","skipToKey","continue","indexName","reverse","openKeyCursor","openCursor","indexeddb_mutation_queue_IndexedDbMutationQueue","IndexedDbMutationQueue","serializer","forUser","uid","isAuthenticated","loadNextBatchIdFromDb","nextBatchId","checkEmpty","empty","maxBatchId","nextUser","IDBKeyRange","keyForBatchId","getNextBatchId","getHighestAcknowledgedBatchId","getLastStreamToken","setLastStreamToken","addMutationBatch","dbBatch","toDbMutationBatch","mutations_1","indexKey","lookupMutationBatch","fromDbMutationBatch","getNextMutationBatchAfterBatchId","max","lowerBound","foundBatch","getAllMutationBatches","dbBatches","getAllMutationBatchesThroughBatchId","getAllMutationBatchesAffectingDocumentKey","documentKey","indexPrefix","indexStart","userID","encodedPath","batchID","mutationKey","getAllMutationBatchesAffectingQuery","queryPath","immediateChildrenLength","uniqueBatchIDs","removeMutationBatches","batches","indexTxn","this_1","batches_1","only","numDeleted","removePromise","performConsistencyCheck","startRange","danglingMutationReferences","gc","indexeddb_query_cache_IndexedDbQueryCache","IndexedDbQueryCache","lastSavedVersion","getHighestTargetId","getLastRemoteSnapshotVersion","setLastRemoteSnapshotVersion","addQueryData","saveQueryData","updateMetadataFromQueryData","saveMetadata","updateQueryData","removeQueryData","removeMatchingKeysForTargetId","toDbTarget","needsUpdate","getQueryData","fromDbTarget","addMatchingKeys","removeMatchingKeys","notifyGCForRemovedKeys","getMatchingKeysForTargetId","indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache","IndexedDbRemoteDocumentCache","addEntry","maybeDocument","toDbRemoteDocument","removeEntry","getEntry","dbRemoteDoc","fromDbRemoteDocument","getDocumentsMatchingQuery","local_serializer_LocalSerializer","LocalSerializer","remoteSerializer","remoteDoc","serializedMutations","m","dbTarget","queryProto","dbTimestamp","EXISTING_OWNER_ERROR_MSG","indexeddb_persistence_IndexedDbPersistence","IndexedDbPersistence","prefix","generateOwnerId","dbName","MAIN_DATABASE","localStoragePrefix","started","simpleDb","tryAcquireOwnerLease","scheduleOwnerLeaseRefreshes","attachWindowUnloadHook","persistenceError","shutdown","detachWindowUnloadHook","stopOwnerLeaseRefreshes","releaseOwnerLease","getMutationQueue","getQueryCache","getRemoteDocumentCache","operation","ensureOwnerLease","buildStoragePrefix","isDefaultDatabase","dbOwner","validOwner","newDbOwner","minAcceptable","maxAcceptable","getZombiedOwnerId","ownerLeaseRefreshHandle","setInterval","reason","clearInterval","windowUnloadHandler","setZombiedOwnerId","addEventListener","removeEventListener","zombiedOwnerId","localStorage","getItem","zombiedOwnerLocalStorageKey","zombieOwnerId","removeItem","setItem","local_documents_view_LocalDocumentsView","LocalDocumentsView","remoteDocumentCache","mutationQueue","getDocument","computeLocalDocument","getDocuments","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionQuery","queryResults","computeLocalDocuments","promisedResults","matchingMutationBatches","matchingKeys","matchingMutationBatches_1","mutatedDoc","remote_document_change_buffer_RemoteDocumentChangeBuffer","RemoteDocumentChangeBuffer","assertChanges","bufferedEntry","local_store_LocalStore","persistence","initialUser","localViewReferences","heldBatchResults","remoteDocuments","queryCache","localDocuments","startMutationQueue","startQueryCache","oldBatches","promisedOldBatches","newBatches","changedKeys","_d","highestAck","ackedBatches","promisedBatch","changedDocuments","affected","shouldHoldBatchResult","documentBuffer_1","releaseBatchResults","promisedAffectedKeys","toReject","affectedKeys","promisedToReject","lastAcked","removeMutationBatch","documentBuffer","changedDocKeys","existingDoc","lastRemoteVersion","remoteVersion","releasedWriteKeys","releaseHeldBatchResults","promisedReleasedWriteKeys","viewChanges","viewChanges_1","nextMutationBatch","afterBatchId","readDocument","cached","documentBuffer_2","garbage","toRelease","isRemoteUpToVersion","batchResults","promiseChain","batchResults_1","applyWriteToRemoteDocuments","affectedDocs","batches_2","docKeys","ackVersion","memory_mutation_queue_MemoryMutationQueue","MemoryMutationQueue","highestAcknowledgedBatchId","batchesByDocumentKey","batchIndex","indexOfExistingBatchId","findMutationBatch","rawIndex","indexOfBatchId","getAllLiveMutationBatchesBeforeIndex","endIndex","immediateChildrenPathLength","startPath","rowKeyPath","batchCount","firstBatchId","queueCount","startIndex","queueIndex","length_1","references","memory_query_cache_MemoryQueryCache","MemoryQueryCache","memory_remote_document_cache_MemoryRemoteDocumentCache","MemoryRemoteDocumentCache","iterator","memory_persistence_MemoryPersistence","MemoryPersistence","mutationQueues","queue","MemoryPersistenceTransaction","no_op_garbage_collector_NoOpGarbageCollector","NoOpGarbageCollector","Deferred","PersistentStreamState","async_queue_DelayedOperation","DelayedOperation","asyncQueue","timerId","targetTimeMs","removalCallback","deferred","createAndSchedule","delayMs","targetTime","delayedOp","timerHandle","handleDelayElapsed","skipDelay","cancel","clearTimeout","enqueue","async_queue_AsyncQueue","AsyncQueue","tail","delayedOperations","operationInProgress","verifyNotFailed","newTail","stack","enqueueAfterDelay","containsDelayedOperation","removeDelayedOperation","verifyOperationInProgress","drain","findIndex","runDelayedOperationsEarly","lastTimerId","All","a","b","backoff_ExponentialBackoff","ExponentialBackoff","initialDelayMs","backoffFactor","maxDelayMs","timerPromise","reset","currentBaseMs","resetToMax","backoffAndRun","delayWithJitterMs","jitterDelayMs","BACKOFF_INITIAL_DELAY_MS","BACKOFF_MAX_DELAY_MS","BACKOFF_FACTOR","persistent_stream_PersistentStream","PersistentStream","connectionTimerId","idleTimerId","connection","credentialsProvider","inactivityTimerPromise","stream","backoff","Initial","isStarted","Backoff","Auth","Open","isOpen","performBackoff","auth","stop","Stopped","inhibitBackoff","markIdle","handleIdleCloseTimer","sendRequest","cancelIdleCheck","finalState","tearDown","getToken","startStream","rpcError","handleStreamClose","dispatchIfStillActive","currentStream_1","startRpc","persistent_stream_PersistentListenStream","PersistentListenStream","ListenStreamConnectionBackoff","ListenStreamIdle","watchChangeProto","onWatchChange","watch","addTarget","labels","unwatch","removeTarget","persistent_stream_PersistentWriteStream","PersistentWriteStream","WriteStreamConnectionBackoff","WriteStreamIdle","handshakeComplete_","writeMutations","responseProto","writeResults","commitTime","onMutationResult","onHandshakeComplete","writeHandshake","writes","datastore_Datastore","Datastore","newPersistentWriteStream","newPersistentWatchStream","params","response","lookup","transaction_Transaction","Transaction","datastore","readVersions","committed","recordVersion","docVersion","existingVersion","preconditionForUpdate","toMutations","unwritten","online_state_tracker_OnlineStateTracker","OnlineStateTracker","onlineStateHandler","watchStreamFailures","onlineStateTimer","shouldWarnClientIsOffline","handleWatchStreamStart","setAndBroadcast","OnlineStateTimeout","logClientOfflineWarningIfNecessary","handleWatchStreamFailure","Online","clearOnlineStateTimer","newState","remote_store_RemoteStore","RemoteStore","pendingWrites","lastBatchSeen","accumulatedWatchChanges","watchStream","writeStream","onlineStateTracker","enableNetwork","isNetworkEnabled","shouldStartWatchStream","startWatchStream","disableNetwork","disableNetworkInternal","cleanUpWatchStreamState","cleanUpWriteStreamState","sendWatchRequest","sendUnwatchRequest","recordPendingTargetRequest","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","handleTargetError","handleWatchChangeBatch","aggregator","deletedDoc","trackedRemote","newQueryData","requestQueryData","canWriteMutations","outstandingWrites","shouldStartWriteStream","startWriteStream","handshakeComplete","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","shift","success","errorHandling","handleWriteError","handleHandshakeError","firestore_client_FirestoreClient","FirestoreClient","usePersistence","initializationDone","persistenceResult","initialized","setUserChangeListener","initializePersistence","initializeRest","startIndexedDbPersistence","canFallback","console","warn","startMemoryPersistence","storagePrefix","onlineStateChangedHandler","eventMgr","removeUserChangeListener","observer","AsyncObserver","muted","scheduleEvent","mute","eventHandler","User","otherUser","GOOGLE_CREDENTIALS","FIRST_PARTY","OAuthToken","Authorization","EmptyCredentialsProvider","userListener","forceRefresh","credentials_FirebaseCredentialsProvider","FirebaseCredentialsProvider","tokenListener","userCounter","newUser","getUser","addAuthTokenListener","initialUserCounter","tokenData","accessToken","removeAuthTokenListener","getUid","currentUid","credentials_FirstPartyToken","FirstPartyToken","gapi","X-Goog-AuthUser","FirstPartyCredentialsProvider","field_value_DeleteFieldValueImpl","serverTimestamp","field_value_ServerTimestampFieldValueImpl","DeleteFieldValueImpl","ServerTimestampFieldValueImpl","PublicFieldValue","RESERVED_FIELD_REGEX","user_data_converter_ParsedSetData","ParsedSetData","user_data_converter_ParsedUpdateData","ParsedUpdateData","user_data_converter_ParseContext","ParseContext","arrayElement","validatePath","childContextForField","childPath","validatePathSegment","childContextForFieldPath","childContextForArray","fieldDescription","user_data_converter_UserDataConverter","UserDataConverter","preConverter","parseSetData","updateData","parseData","parseMergeData","parseUpdateData","fieldMaskPaths","childContext","runPreConverter","parsedValue","mask","parseUpdateVarargs","moreFieldsAndValues","value_1","parseQueryValue","parsed","parseArray","parseObject","parseScalarValue","entryIndex","array_1","entry","parsedEntry","DEFAULT_HOST","DEFAULT_SSL","database_FirestoreSettings","FirestoreSettings","settings","FirestoreConfig","Firestore","databaseIdOrApp","_queue","_firestoreClient","config","firebaseApp","databaseIdFromApp","external_1","_config","_databaseId","settingsLiteral","newSettings","ensureClientConfigured","enablePersistence","configureClient","thisDb","otherDb","_key","_dataConverter","collection","pathString","database_CollectionReference","forPath","database_Transaction","database_WriteBatch","level","_firestore","_transaction","database_DocumentSnapshot","fieldOrUpdateData","WriteBatch","_mutations","_committed","verifyNotCommitted","DocumentReference","onSnapshot","includeMetadataChanges","currArg","internalOptions","complete","onSnapshotInternal","errHandler","asyncObserver","internalListener","SnapshotMetadata","DocumentSnapshot","_document","_fromCache","convertObject","convertValue","convertArray","QueryDocumentSnapshot","database_Query","_query","opStr","validateNewFilter","directionStr","validateNewOrderBy","docOrField","boundFromDocOrFields","startAfter","endBefore","boundFromDocument","allFields","boundFromFields","components","rawValue","wrapped","database_QuerySnapshot","firestoreClient","existingField","validateOrderByAndInequalityMatch","inequality","QuerySnapshot","_originalQuery","_snapshot","_cachedChanges","thisArg","convertToDocumentImpl","CollectionReference","parentPath","docRef","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","117","global","l","aa","ba","propertyIsEnumerable","ca","da","ea","ha","ia","d","unshift","Function","ja","t","H","Db","ka","captureStackTrace","la","ma","u","na","pa","fa","sa","ta","va","wa","xa","za","x","w","Ca","Da","Ea","Fa","Ha","Ga","Ia","Ja","Ka","Qa","documentMode","Va","ya","Ra","h","parseInt","z","bb","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","Oa","nodeName","fromElement","toElement","pageX","pageY","defaultPrevented","fb","proxy","src","capture","ga","eb","Z","gb","hb","jb","qa","ib","nb","once","ob","pb","qb","rb","kb","sb","ab","attachEvent","tb","addListener","removeListener","mb","ub","Za","vb","wb","detachEvent","lb","xb","yb","keyCode","returnValue","parentNode","zb","handleEvent","A","N","J","Ab","Bb","Cb","eval","Eb","Fb","Boolean","Gb","valueOf","Ib","Hb","Jb","Kb","Ob","Pb","Mb","Qb","Sb","MessageChannel","postMessage","createElement","style","display","documentElement","appendChild","contentWindow","location","protocol","origin","port1","onmessage","port2","onreadystatechange","removeChild","Ub","Tb","Vb","setImmediate","Window","Rb","Nb","Wb","Xb","g","r","Yb","O","Zb","$b","ac","Y","bc","dc","cc","ec","fc","hc","B","nc","qc","pc","oc","lc","lastIndexOf","C","log","jc","rc","kc","D","mc","sc","tc","E","I","W","Lb","uc","F","vc","wc","G","xc","ic","parse","yc","zc","dispatchEvent","Ac","K","Bc","Cc","Dc","Gc","Ic","Jc","Kc","Lc","Mc","Oc","Pc","ActiveXObject","XMLHttpRequest","L","T","R","Qc","Na","S","j","U","o","X","Rc","Uc","Vc","M","Wc","Xc","Yc","Zc","$c","V","ad","bd","cd","dd","ed","fd","gd","hd","Tc","Sc","jd","$","kd","ld","ra","nd","od","P","md","qd","decodeURIComponent","Q","rd","sd","td","ud","vd","match","pd","wd","xd","Dd","yd","Ed","Fd","abs","Gd","Hd","decodeURI","encodeURI","Id","Kd","Jd","Ld","toLowerCase","Md","Od","Nd","Pd","Qd","Rd","Sd","Td","Vd","Wd","Xd","Yd","Zd","$d","oa","La","ae","be","ce","de","ee","fe","ge","he","ie","je","encodeURIComponent","ke","Image","onload","le","ontimeout","me","re","y","timeout","pe","se","te","ue","goog","Ma","self","ne","qe","readyState","getResponseHeader","ve","we","xe","Ua","concurrentRequestLimit","fastHandshake","ye","ze","Ae","sendBeacon","Be","Ce","De","Ee","Pa","Fe","Ge","Ie","He","round","Wa","Je","Ke","Le","Ud","Aa","Me","hostname","port","Ne","Oe","Pe","testUrl","messageHeaders","clientProtocolHeaderRequired","X-Client-Protocol","messageContentType","X-WebChannel-Content-Type","X-WebChannel-Client-Profile","Qe","Re","__sm__","Se","Ue","Ve","We","Xe","Ye","$e","Ze","af","bf","cf","df","trim","Ba","Sa","Ta","parseFloat","Xa","compatMode","Ya","freeze","$a","2","3","4","preventDefault","\"","\\","/","\b","\f","\n","\r","\t","\u000b","Ec","Fc","Hc","Nc","zd","Ad","Bd","Cd","oe","toUpperCase","FormData","setRequestHeader","responseType","withCredentials","statusText","responseText","__data__","Te","createWebChannelTransport","ErrorCode","WebChannel","XhrIoPool","22","instances","inst","defaultLogLevel","INFO","defaultLogHandler","logType","toISOString","VERBOSE","WARN","Logger","_logLevel","_logHandler","TypeError"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IAExBC,IACA,SAAUC,EAAQC,EAASC,GCOjCA,EAAA,MDgBMC,IACA,SAAUH,EAAQI,EAAqBF,GAE7C,YERA,SAAAG,KACA,MAAAC,IAAAC,WAAAC,GAAA,SAAAC,MACAC,GAAAD,MAEAH,GAAAC,WAAAC,GAAA,SAAAG,OACAD,GAAAC,OAGAD,GAAAE,MAGA,QAAAC,GAAAC,GAIA,OAAAA,GACA,IAAAJ,IAAAD,MACAH,GAAAC,SAAAC,GAAA,SAAAC,KACA,MACA,KAAAC,IAAAE,MACAN,GAAAC,SAAAC,GAAA,SAAAI,KACA,MACA,KAAAF,IAAAC,OACAL,GAAAC,SAAAC,GAAA,SAAAG,MACA,MACA,SACAL,GAAAS,MAAA,cAAAC,GAAA,6CAGA,QAAAC,GAAAC,EAAAC,GAEA,OADAC,MACAC,EAAA,EAAoBA,EAAAC,UA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,KAEAw3E,EAAA/1E,UAAAkvD,KAAA,WAEA,OADA3wD,MACAH,EAAA,EAAwBA,EAAAC,UAAAC,OAAuBF,IAC/CG,EAAAH,GAAAC,UAAAD,EAEAiW,MAAA4hE,GAAAv3E,MAAA2V,WAAA5W,EAAAq4E,MAAAn3E,OAAAJ,KAEAw3E,EAAA/1E,UAAAlC,MAAA,WAEA,OADAS,MACAH,EAAA,EAAwBA,EAAAC,UAAAC,OAAuBF,IAC/CG,EAAAH,GAAAC,UAAAD,EAEAiW,MAAA4hE,GAAAv3E,MAAA2V,WAAA5W,EAAAE,OAAAgB,OAAAJ,KAEAw3E,ItFu/hBiC54E,GAAiC,YAAIS,EACvCX,EAAoBk+D,EAAEh+D,EAAqB,SAAU,WAAa,MAAO44E,KqFhqiBxG94E,EAAAk+D,EAAAh+D,EAAA,4BAAAM,QrF8riBG,MACO,MAAMK,GACN,KAAUuB,OACR","file":"firebase-firestore.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([1],{\n\n/***/ 115:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(116);\n\n\n/***/ }),\n\n/***/ 116:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/version.js\n/**\n * Copyright 2017 Google Inc.\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 semver (www.semver.org) version of the SDK. */\nvar SDK_VERSION = esm[\"default\"].SDK_VERSION;\n\n//# sourceMappingURL=version.js.map\n\n// EXTERNAL MODULE: ../logger/dist/esm/index.js + 1 modules\nvar dist_esm = __webpack_require__(22);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/log.js\n/**\n * Copyright 2017 Google Inc.\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/* tslint:disable:no-console */\n\n\n\nvar logClient = new dist_esm[\"Logger\"]('@firebase/firestore');\nvar LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n// Helper methods are needed because variables can't be exported as read/write\nfunction getLogLevel() {\n if (logClient.logLevel === dist_esm[\"LogLevel\"].DEBUG) {\n return LogLevel.DEBUG;\n }\n else if (logClient.logLevel === dist_esm[\"LogLevel\"].SILENT) {\n return LogLevel.SILENT;\n }\n else {\n return LogLevel.ERROR;\n }\n}\nfunction setLogLevel(newLevel) {\n /**\n * Map the new log level to the associated Firebase Log Level\n */\n switch (newLevel) {\n case LogLevel.DEBUG:\n logClient.logLevel = dist_esm[\"LogLevel\"].DEBUG;\n break;\n case LogLevel.ERROR:\n logClient.logLevel = dist_esm[\"LogLevel\"].ERROR;\n break;\n case LogLevel.SILENT:\n logClient.logLevel = dist_esm[\"LogLevel\"].SILENT;\n break;\n default:\n logClient.error(\"Firestore (\" + SDK_VERSION + \"): Invalid value passed to `setLogLevel`\");\n }\n}\nfunction debug(tag, msg) {\n var obj = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n if (logClient.logLevel <= dist_esm[\"LogLevel\"].DEBUG) {\n var args = obj.map(argToString);\n logClient.debug.apply(logClient, [\"Firestore (\" + SDK_VERSION + \") [\" + tag + \"]: \" + msg].concat(args));\n }\n}\nfunction log_error(msg) {\n var obj = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n if (logClient.logLevel <= dist_esm[\"LogLevel\"].ERROR) {\n var args = obj.map(argToString);\n logClient.error.apply(logClient, [\"Firestore (\" + SDK_VERSION + \"): \" + msg].concat(args));\n }\n}\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n }\n else {\n var platform = platform_PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n }\n catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n\n//# sourceMappingURL=log.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/assert.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nfunction fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n log_error(message);\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 new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nfunction assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n\n//# sourceMappingURL=assert.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform/platform.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nvar platform_PlatformSupport = /** @class */ (function () {\n function PlatformSupport() {\n }\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n };\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n };\n return PlatformSupport;\n}());\n\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nfunction emptyByteString() {\n return platform_PlatformSupport.getPlatform().emptyByteString;\n}\n\n//# sourceMappingURL=platform.js.map\n\n// EXTERNAL MODULE: /tmp/tmp-208812ou3wR5n5ZCvd/node_modules/tslib/tslib.es6.js\nvar tslib_es6 = __webpack_require__(2);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/error.js\n/**\n * Copyright 2017 Google Inc.\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// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\nvar Code = {\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 class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nvar error_FirestoreError = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](FirestoreError, _super);\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError';\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 = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\n return _this;\n }\n return FirestoreError;\n}(Error));\n\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/api.js\n/**\n * Copyright 2017 Google Inc.\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// We are doing some heavy reflective stuff, lots of any casting necessary\n/* tslint:disable:no-any */\n\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nfunction makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n // Copy any static methods/members\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n return PublicConstructor;\n}\n\n//# sourceMappingURL=api.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/obj.js\n/**\n * Copyright 2017 Google Inc.\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\nfunction contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nfunction get(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\nfunction obj_size(obj) {\n var count = 0;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nfunction defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\nfunction forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\nfunction forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\nfunction lookupOrInsert(obj, key, valFn) {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\nfunction isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nfunction shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=obj.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/input_validation.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nfunction validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nfunction validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nfunction validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nfunction validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nfunction validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nfunction validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n var actualDescription = valueDescription(input);\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', '));\n}\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nfunction validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nfunction isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nfunction valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nfunction tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nfunction validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nfunction validateOptionNames(functionName, options, optionNames) {\n forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nfunction invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/misc.js\n/**\n * Copyright 2017 Google Inc.\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// tslint:disable-next-line:class-as-namespace\nvar misc_AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\n\nfunction primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nfunction equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using isEqual(). */\nfunction arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nfunction immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nfunction immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/blob.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new error_FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!platform_PlatformSupport.getPlatform().base64Available) {\n throw new error_FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar blob_Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = platform_PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return platform_PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n Blob.prototype.isEqual = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nvar PublicBlob = makeConstructorPrivate(blob_Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/geo_point.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar geo_point_GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n GeoPoint.prototype.isEqual = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\n\n\n//# sourceMappingURL=geo_point.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/database_info.js\n/**\n * Copyright 2017 Google Inc.\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\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\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 */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\n\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar database_info_DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.isEqual = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\n\n\n//# sourceMappingURL=database_info.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/path.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar path_Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.isEqual = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar path_ResourcePath = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\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 ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\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 if (path.indexOf('//') >= 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(path_Path));\n\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar path_FieldPath = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_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 */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(path_Path));\n\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_key.js\n/**\n * Copyright 2017 Google Inc.\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\nvar document_key_DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.isEqual = function (other) {\n return (other !== null && path_ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return path_ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new path_ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(path_ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new path_ResourcePath([]));\n return DocumentKey;\n}());\n\n\n//# sourceMappingURL=document_key.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document.js\n/**\n * Copyright 2017 Google Inc.\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\nvar document_Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.isEqual = function (other) {\n return (other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.data.isEqual(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\n\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar document_NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.isEqual = function (other) {\n return (other &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\n\n\n//# sourceMappingURL=document.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_map.js\n/**\n * Copyright 2017 Google Inc.\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 sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : sorted_map_LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, sorted_map_LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\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 SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\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 SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\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 SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n // Returns an iterator over the SortedMap.\n SortedMap.prototype.getIterator = function () {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, false);\n };\n SortedMap.prototype.getIteratorFrom = function (key) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, false);\n };\n SortedMap.prototype.getReverseIterator = function () {\n return new sorted_map_SortedMapIterator(this.root, null, this.comparator, true);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\n return new sorted_map_SortedMapIterator(this.root, key, this.comparator, true);\n };\n return SortedMap;\n}()); // end SortedMap\n\n// An iterator over an LLRBNode.\nvar sorted_map_SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\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(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nvar sorted_map_LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\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 LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\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 LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\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 LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new sorted_map_LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\n\nsorted_map_LLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/field_value.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder || (TypeOrder = {}));\n/** Defines the return value for pending server timestamps. */\nvar ServerTimestampBehavior;\n(function (ServerTimestampBehavior) {\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\n/** Holds properties that define field value deserialization options. */\nvar field_value_FieldValueOptions = /** @class */ (function () {\n function FieldValueOptions(serverTimestampBehavior) {\n this.serverTimestampBehavior = serverTimestampBehavior;\n }\n FieldValueOptions.fromSnapshotOptions = function (options) {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(ServerTimestampBehavior.Estimate);\n case 'previous':\n return new FieldValueOptions(ServerTimestampBehavior.Previous);\n case 'none': // Fall-through intended.\n case undefined:\n return FieldValueOptions.defaultOptions;\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n };\n FieldValueOptions.defaultOptions = new FieldValueOptions(ServerTimestampBehavior.Default);\n return FieldValueOptions;\n}());\n\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar field_value_FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\n\nvar field_value_NullValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function (options) {\n return null;\n };\n NullValue.prototype.isEqual = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(field_value_FieldValue));\n\nvar field_value_BooleanValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BooleanValue.prototype.isEqual = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(field_value_FieldValue));\n\n/** Base class for IntegerValue and DoubleValue. */\nvar field_value_NumberValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function (options) {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(field_value_FieldValue));\n\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar field_value_IntegerValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(field_value_NumberValue));\n\nvar field_value_DoubleValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(field_value_NumberValue));\n\n// TODO(b/37267885): Add truncation support\nvar field_value_StringValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function (options) {\n return this.internalValue;\n };\n StringValue.prototype.isEqual = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(field_value_FieldValue));\n\nvar field_value_TimestampValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function (options) {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.isEqual = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof field_value_ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(field_value_FieldValue));\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * 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 */\nvar field_value_ServerTimestampValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime, previousValue) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.previousValue = previousValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function (options) {\n if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\n return this.localWriteTime.toDate();\n }\n else if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\n return this.previousValue ? this.previousValue.value(options) : null;\n }\n else {\n return null;\n }\n };\n ServerTimestampValue.prototype.isEqual = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof field_value_TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(field_value_FieldValue));\n\nvar field_value_BlobValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BlobValue.prototype.isEqual = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(field_value_FieldValue));\n\nvar field_value_RefValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function (options) {\n return this.key;\n };\n RefValue.prototype.isEqual = function (other) {\n if (other instanceof RefValue) {\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : document_key_DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(field_value_FieldValue));\n\nvar field_value_GeoPointValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function (options) {\n return this.internalValue;\n };\n GeoPointValue.prototype.isEqual = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(field_value_FieldValue));\n\nvar field_value_ObjectValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function (options) {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value(options);\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.isEqual = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\n return ObjectValue;\n}(field_value_FieldValue));\n\nvar field_value_ArrayValue = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function (options) {\n return this.internalValue.map(function (v) { return v.value(options); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.isEqual = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(field_value_FieldValue));\n\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/types.js\n/**\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nvar isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction isNullOrUndefined(value) {\n return value === null || value === undefined;\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 */\nfunction isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nfunction safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/query.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar query_Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\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 if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new query_OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof query_RelationFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!document_key_DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\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.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.isEqual = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return document_key_DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (document_key_DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\n\nvar query_RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.isEqual = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\n\nvar query_RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof field_value_RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = document_key_DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case query_RelationOp.LESS_THAN:\n return comparison < 0;\n case query_RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case query_RelationOp.EQUAL:\n return comparison === 0;\n case query_RelationOp.GREATER_THAN:\n return comparison > 0;\n case query_RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== query_RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\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 (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.isEqual = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\n\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.isEqual = function (other) {\n if (other instanceof NullFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\n\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.isEqual = function (other) {\n if (other instanceof NanFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\n\n/**\n * Creates a filter based on the provided arguments.\n */\nfunction fieldFilter(field, op, value) {\n if (value.isEqual(field_value_NullValue.INSTANCE)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.isEqual(field_value_DoubleValue.NAN)) {\n if (op !== query_RelationOp.EQUAL) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new query_RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\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 */\nvar query_Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof field_value_RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = document_key_DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.isEqual = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.isEqual(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar query_OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? document_Document.compareByKey(d1, d2)\n : document_Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.isEqual = function (other) {\n return this.dir === other.dir && this.field.isEqual(other.field);\n };\n return OrderBy;\n}());\n\nvar KEY_ORDERING_ASC = new query_OrderBy(path_FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new query_OrderBy(path_FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/timestamp.js\n/**\n * Copyright 2017 Google Inc.\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\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar timestamp_Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\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 var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.isEqual = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\n\n\n//# sourceMappingURL=timestamp.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/snapshot_version.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar snapshot_version_SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new timestamp_Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.isEqual = function (other) {\n return this.timestamp.isEqual(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new timestamp_Timestamp(0, 0));\n return SnapshotVersion;\n}());\n\n\n//# sourceMappingURL=snapshot_version.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/query_data.js\n/**\n * Copyright 2017 Google Inc.\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\n/** An enumeration of the different purposes we have for queries. */\nvar QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar query_data_QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = snapshot_version_SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.isEqual = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.isEqual(other.query));\n };\n return QueryData;\n}());\n\n\n//# sourceMappingURL=query_data.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\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 */\nvar mutation_FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.isEqual = function (other) {\n return arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\n\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\n\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.isEqual = function (other) {\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\n };\n return FieldTransform;\n}());\n\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\n\nvar MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType || (MutationType = {}));\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 */\nvar mutation_Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof document_Document &&\n maybeDoc.version.isEqual(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof document_Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof document_NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.isEqual = function (other) {\n return (equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\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 it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we 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 null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar mutation_Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n return maybeDoc.version;\n }\n else {\n return snapshot_version_SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar mutation_SetMutation = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\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 var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n return new document_Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.isEqual = function (other) {\n return (other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition));\n };\n return SetMutation;\n}(mutation_Mutation));\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 */\nvar mutation_PatchMutation = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = mutation_Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new document_Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.isEqual = function (other) {\n return (other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof document_Document) {\n data = maybeDoc.data;\n }\n else {\n data = field_value_ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(mutation_Mutation));\n\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar mutation_TransformMutation = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = mutation_Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new document_Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.isEqual = function (other) {\n return (other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof document_Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\n return doc;\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 * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n var previousValue = null;\n if (baseDoc instanceof document_Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n transformResults.push(new field_value_ServerTimestampValue(localWriteTime, previousValue));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(mutation_Mutation));\n\n/** A mutation that deletes the document at the given key. */\nvar mutation_DeleteMutation = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\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 return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\n }\n return new document_NoDocument(this.key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.isEqual = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition));\n };\n return DeleteMutation;\n}(mutation_Mutation));\n\n\n//# sourceMappingURL=mutation.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/existence_filter.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.isEqual = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\n\n\n//# sourceMappingURL=existence_filter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/rpc_error.js\n/**\n * Copyright 2017 Google Inc.\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\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.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nfunction isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\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 */\nfunction mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\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 mapCodeFromRpcCode(code) {\n if (code === undefined) {\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 log_error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nfunction mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nfunction mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/sorted_set.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar sorted_set_SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.isEqual = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\n\n\n//# sourceMappingURL=sorted_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/collections.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(document_key_DocumentKey.comparator);\nfunction maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new SortedMap(document_key_DocumentKey.comparator);\nfunction documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(document_key_DocumentKey.comparator);\nfunction documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new sorted_set_SortedSet(document_key_DocumentKey.comparator);\nfunction documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_event.js\n/**\n * Copyright 2017 Google Inc.\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\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 */\nvar remote_event_RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \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 documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: snapshot_version_SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\n\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nvar CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.isEqual = function (other) {\n return other !== null && this.docs.isEqual(other.docs);\n };\n return ResetMapping;\n}());\n\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.isEqual = function (other) {\n return (other !== null &&\n this.addedDocuments.isEqual(other.addedDocuments) &&\n this.removedDocuments.isEqual(other.removedDocuments));\n };\n return UpdateMapping;\n}());\n\n\n//# sourceMappingURL=remote_event.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/watch_change.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\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 */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \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 newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\n\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\n\nvar WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar watch_change_WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar watch_change_WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof watch_change_WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new remote_event_RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!contains(this.pendingTargetResponses, targetId) &&\n contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!contains(_this.pendingTargetResponses, targetId)) {\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 change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\n\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/serializer.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[query_RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[query_RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[query_RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[query_RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[query_RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return Number(value);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar serializer_JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new error_FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a number (or undefined) 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: } struct.\n */\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\n if (!isNullOrUndefined(val)) {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n return { value: val };\n }\n else {\n return undefined;\n }\n };\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\n var result;\n if (typeof val === 'object') {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n result = val.value;\n }\n else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\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 (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return timestamp_Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new timestamp_Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return blob_Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return blob_Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return snapshot_version_SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = path_ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new document_key_DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return path_ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new path_ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new path_ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof field_value_NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof field_value_BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof field_value_IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof field_value_DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof field_value_StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof field_value_ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof field_value_ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof field_value_TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof field_value_GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof field_value_BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof field_value_RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return field_value_NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return field_value_BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new field_value_IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return field_value_DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return field_value_DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return field_value_DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new field_value_DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new field_value_StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new field_value_ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new field_value_TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new field_value_GeoPointValue(new geo_point_GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new field_value_BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new database_info_DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new document_key_DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new field_value_RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new document_Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = field_value_ObjectValue.EMPTY;\n forEach(map, function (key, value) {\n result = result.set(new path_FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new document_Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new document_NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof document_Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof document_NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof watch_change_WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new watch_change_WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new document_Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : snapshot_version_SnapshotVersion.forDeletedDoc();\n var doc = new document_NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\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 // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return snapshot_version_SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof mutation_SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof mutation_DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof mutation_PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof mutation_TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : mutation_Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new mutation_PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new mutation_SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new mutation_DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new mutation_TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return mutation_Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return mutation_Precondition.exists(precondition.exists);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = path_FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return query_Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(path_ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toInt32Value(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new query_Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof query_RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new query_Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return query_RelationOp.EQUAL;\n case 'GREATER_THAN':\n return query_RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return query_RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return query_RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return query_RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return path_FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new query_OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof query_RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new query_RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return path_FieldPath.fromServerFormat(path); });\n return new mutation_FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\n\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n// EXTERNAL MODULE: ../webchannel-wrapper/dist/index.js\nvar dist = __webpack_require__(117);\nvar dist_default = /*#__PURE__*/__webpack_require__.n(dist);\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/stream_bridge.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar stream_bridge_StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\n\n\n//# sourceMappingURL=stream_bridge.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar LOG_TAG = 'Connection';\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\nvar RPC_URL_VERSION = 'v1beta1';\n/** Maps RPC names to the corresponding REST endpoint name. */\nvar RPC_NAME_REST_MAPPING = {\n BatchGetDocuments: 'batchGet',\n Commit: 'commit'\n};\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar webchannel_connection_WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new dist[\"XhrIoPool\"]();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n };\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(dist[\"EventType\"].COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case dist[\"ErrorCode\"].NO_ERROR:\n var json = xhr.getResponseJson();\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case dist[\"ErrorCode\"].TIMEOUT:\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(new error_FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case dist[\"ErrorCode\"].HTTP_ERROR:\n var status_1 = xhr.getStatus();\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new error_FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(new error_FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(rpcName, request, token);\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n var webchannelTransport = Object(dist[\"createWebChannelTransport\"])();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n // Send our custom headers as a '$httpHeaders=' url param to avoid CORS\n // preflight round-trip. This is formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L40\n httpHeadersOverwriteParam: '$httpHeaders',\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: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\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 var opened = false;\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 var closed = false;\n var streamBridge = new stream_bridge_StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\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 var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(dist[\"WebChannel\"].EventType.OPEN, function () {\n if (!closed) {\n debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new error_FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(dist[\"WebChannel\"].EventType.MESSAGE, function (msg) {\n if (!closed) {\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\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 var error = \n // tslint:disable-next-line:no-any msgData.error is not typed.\n msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new error_FirestoreError(code, message));\n channel.close();\n }\n else {\n debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\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 streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(urlRpcName);\n return url.join('');\n };\n return WebChannelConnection;\n}());\n\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_platform.js\n/**\n * Copyright 2017 Google Inc.\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\nvar browser_platform_BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new webchannel_connection_WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new serializer_JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.formatJSON = function (value) {\n return JSON.stringify(value);\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\n\n\n//# sourceMappingURL=browser_platform.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform_browser/browser_init.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nplatform_PlatformSupport.setPlatform(new browser_platform_BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_path.js\n/**\n * Copyright 2017 Google Inc.\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\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar field_path_FieldPath = /** @class */ (function () {\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 function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new path_FieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n FieldPath.prototype.isEqual = function (other) {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(path_FieldPath.keyField().canonicalString());\n return FieldPath;\n}());\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nfunction fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (field_path_FieldPath.bind.apply(field_path_FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/types.js\n/**\n * Copyright 2017 Google Inc.\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 * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nvar OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n OnlineState[OnlineState[\"Online\"] = 1] = \"Online\";\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n OnlineState[OnlineState[\"Offline\"] = 2] = \"Offline\";\n})(OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view_snapshot.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType || (ChangeType = {}));\nvar SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar view_snapshot_DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new SortedMap(document_key_DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\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('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\n\nvar ViewSnapshot = /** @class */ (function () {\n function ViewSnapshot(query, docs, oldDocs, docChanges, fromCache, hasPendingWrites, syncStateChanged) {\n this.query = query;\n this.docs = docs;\n this.oldDocs = oldDocs;\n this.docChanges = docChanges;\n this.fromCache = fromCache;\n this.hasPendingWrites = hasPendingWrites;\n this.syncStateChanged = syncStateChanged;\n }\n ViewSnapshot.prototype.isEqual = function (other) {\n if (this.fromCache !== other.fromCache ||\n this.hasPendingWrites !== other.hasPendingWrites ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)) {\n return false;\n }\n var changes = this.docChanges;\n var otherChanges = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (var i = 0; i < changes.length; i++) {\n if (changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\n return false;\n }\n }\n return true;\n };\n return ViewSnapshot;\n}());\n\n\n//# sourceMappingURL=view_snapshot.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/document_set.js\n/**\n * Copyright 2017 Google Inc.\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\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 */\nvar document_set_DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return document_key_DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\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 */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\n\n\n//# sourceMappingURL=document_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/obj_map.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar obj_map_ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return isEmpty(this.inner);\n };\n return ObjectMap;\n}());\n\n\n//# sourceMappingURL=obj_map.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/event_manager.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar event_manager_EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.applyOnlineStateChange(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var query, lastListen, queryInfo, i;\n return tslib_es6[\"__generator\"](this, function (_a) {\n query = listener.query;\n lastListen = false;\n queryInfo = this.queries.get(query);\n if (queryInfo) {\n i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return [2 /*return*/, this.syncEngine.unlisten(query)];\n }\n return [2 /*return*/];\n });\n });\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.applyOnlineStateChange(onlineState);\n }\n });\n };\n return EventManager;\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 */\nvar event_manager_QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\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.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.fromCache, snap.hasPendingWrites, snap.syncStateChanged);\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\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 (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\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 return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = new ViewSnapshot(snap.query, snap.docs, document_set_DocumentSet.emptySet(snap.docs), QueryListener.getInitialViewChanges(snap), snap.fromCache, snap.hasPendingWrites, true);\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\n\n\n//# sourceMappingURL=event_manager.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/persistence_promise.js\n/**\n * Copyright 2017 Google Inc.\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/**\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 */\nvar persistence_promise_PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\n this.nextCallback = null;\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = undefined;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_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(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n // tslint:disable-next-line:no-any\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\n all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n // tslint:disable-next-line:no-any\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\n\n\n//# sourceMappingURL=persistence_promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/eager_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar eager_garbage_collector_EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return persistence_promise_PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = persistence_promise_PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return persistence_promise_PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\n\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_view_changes.js\n/**\n * Copyright 2017 Google Inc.\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\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 */\nvar local_view_changes_LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\n\n\n//# sourceMappingURL=local_view_changes.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/reference_set.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\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 */\nvar reference_set_ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new sorted_set_SortedSet(reference_set_DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new reference_set_DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new reference_set_DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = document_key_DocumentKey.EMPTY;\n var startRef = new reference_set_DocReference(emptyKey, id);\n var endRef = new reference_set_DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(firstRef !== null && key.isEqual(firstRef.key));\n };\n return ReferenceSet;\n}());\n\nvar reference_set_DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (document_key_DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n document_key_DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\n\n\n//# sourceMappingURL=reference_set.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/target_id_generator.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\n\n\n//# sourceMappingURL=target_id_generator.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/view.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\n\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\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 */\nvar view_View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\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 = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new document_set_DocumentSet(query.docComparator.bind(query));\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 * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new view_snapshot_DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\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 //\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 var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof document_Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\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 needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n this.applyTargetChange(targetChange);\n var limboChanges = this.updateLimboDocuments();\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, newSyncState === SyncState.Local, !docChanges.mutatedKeys.isEmpty(), syncStateChanged);\n return {\n snapshot: snap,\n limboChanges: limboChanges\n };\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 View.prototype.applyOnlineStateChange = function (onlineState) {\n if (this.current && onlineState === OnlineState.Offline) {\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 = false;\n return this.applyChanges({\n documentSet: this.documentSet,\n changeSet: new view_snapshot_DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n });\n }\n else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\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 */\n View.prototype.applyTargetChange = function (targetChange) {\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n };\n View.prototype.updateLimboDocuments = function () {\n var _this = this;\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\n\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case 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 case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/sync_engine.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar sync_engine_LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \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 view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar sync_engine_SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new obj_map_ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new SortedMap(document_key_DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new reference_set_ReferenceSet();\n this.limboCollector = new eager_garbage_collector_EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\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 targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new view_View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\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 */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\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 some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\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 *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new document_NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState) {\n var newViewSnapshots = [];\n this.queryViewsByQuery.forEach(function (query, queryView) {\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.viewHandler(newViewSnapshots);\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\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 var docMap = new SortedMap(document_key_DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new document_NoDocument(limboKey, snapshot_version_SnapshotVersion.forDeletedDoc()));\n var event_1 = new remote_event_RemoteEvent(snapshot_version_SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\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 this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\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 this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.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 (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n debug(sync_engine_LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n debug(sync_engine_LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = query_Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new query_data_QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\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 return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = local_view_changes_LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\n\n\n//# sourceMappingURL=sync_engine.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/model/mutation_batch.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar mutation_batch_MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var baseDoc = maybeDoc;\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.isEqual = function (other) {\n return (this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\n\n/** The result of applying a mutation batch to the backend. */\nvar mutation_batch_MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\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=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\n\n\n//# sourceMappingURL=mutation_batch.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/encoded_resource_path.js\n/**\n * Copyright 2017 Google Inc.\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\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\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 */\nfunction decode(path) {\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 var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return path_ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\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 var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new path_ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nfunction prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_schema.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\n * Cache\n * 2. Added targetCount to targetGlobal row.\n */\nvar SCHEMA_VERSION = 2;\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 */\nfunction createOrUpgradeDb(db, txn, fromVersion, toVersion) {\n // This function currently supports migrating to schema version 1 (Mutation\n // Queue, Query and Remote Document Cache) and schema version 2 (Query\n // counting).\n assert(fromVersion < toVersion && fromVersion >= 0 && toVersion <= 2, 'Unexpected schema upgrade from v${fromVersion} to v{toVersion}.');\n if (fromVersion < 1 && toVersion >= 1) {\n createOwnerStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createRemoteDocumentCache(db);\n }\n var p = persistence_promise_PersistencePromise.resolve();\n if (fromVersion < 2 && toVersion >= 2) {\n p = ensureTargetGlobalExists(txn).next(function (targetGlobal) {\n return saveTargetCount(txn, targetGlobal);\n });\n }\n return p;\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\n\nfunction createOwnerStore(db) {\n db.createObjectStore(DbOwner.store);\n}\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\n\nfunction createMutationQueue(db) {\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath\n });\n db.createObjectStore(indexeddb_schema_DbDocumentMutation.store);\n}\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar indexeddb_schema_DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\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 DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\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 */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\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 */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\n\nfunction createRemoteDocumentCache(db) {\n db.createObjectStore(DbRemoteDocument.store);\n}\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\n\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion, \n /**\n * The number of targets persisted.\n */\n targetCount) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n this.targetCount = targetCount;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\n\nfunction createQueryCache(db) {\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\n keyPath: DbTargetDocument.keyPath\n });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Counts the number of targets persisted and adds that value to the target\n * global singleton.\n */\nfunction saveTargetCount(txn, metadata) {\n var globalStore = txn.store(DbTargetGlobal.store);\n var targetStore = txn.store(DbTarget.store);\n return targetStore.count().next(function (count) {\n metadata.targetCount = count;\n return globalStore.put(DbTargetGlobal.key, metadata);\n });\n}\n/**\n * Ensures that the target global singleton row exists by adding it if it's\n * missing.\n *\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\n */\nfunction ensureTargetGlobalExists(txn) {\n var globalStore = txn.store(DbTargetGlobal.store);\n return globalStore.get(DbTargetGlobal.key).next(function (metadata) {\n if (metadata != null) {\n return persistence_promise_PersistencePromise.resolve(metadata);\n }\n else {\n metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, snapshot_version_SnapshotVersion.MIN.toTimestamp(), \n /*targetCount=*/ 0);\n return globalStore.put(DbTargetGlobal.key, metadata).next(function () { return metadata; });\n }\n });\n}\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nvar ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n indexeddb_schema_DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/simple_db.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar simple_db_LOG_TAG = 'SimpleDb';\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 */\nvar simple_db_SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(simple_db_LOG_TAG, 'Opening database:', name);\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\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 var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(simple_db_LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n var db = event.target.result;\n // We are provided a version upgrade transaction from the request, so\n // we wrap that in a SimpleDbTransaction to allow use of our friendlier\n // API for schema migration operations.\n var txn = new simple_db_SimpleDbTransaction(request.transaction);\n runUpgrade(db, txn, event.oldVersion, SCHEMA_VERSION).next(function () {\n debug(simple_db_LOG_TAG, 'Database upgrade to version ' + SCHEMA_VERSION + ' complete');\n });\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(simple_db_LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\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 var ua = window.navigator.userAgent;\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 if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = simple_db_SimpleDbTransaction.open(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return persistence_promise_PersistencePromise.reject(error);\n })\n .toPromise();\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 return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\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 */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\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 */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar simple_db_SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(transaction) {\n var _this = this;\n this.transaction = transaction;\n this.aborted = false;\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.open = function (db, mode, objectStoreNames) {\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\n };\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(simple_db_LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore 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 */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new simple_db_SimpleDbStore(store);\n };\n return SimpleDbTransaction;\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 */\nvar simple_db_SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(simple_db_LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\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 * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(simple_db_LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(simple_db_LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\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 */\n SimpleDbStore.prototype.count = function () {\n debug(simple_db_LOG_TAG, 'COUNT', this.store.name);\n var request = this.store.count();\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(simple_db_LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof persistence_promise_PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return persistence_promise_PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new persistence_promise_PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar indexeddb_mutation_queue_IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\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 */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\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 assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isAuthenticated() ? user.uid : '';\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var indexKey = indexeddb_schema_DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, indexeddb_schema_DbDocumentMutation.PLACEHOLDER);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n // All batches with batchId <= this.metadata.lastAcknowledgedBatchId have\n // been acknowledged so the first unacknowledged batch after batchID will\n // have a batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, this.metadata.lastAcknowledgedBatchId) + 1;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(nextBatchId));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId >= nextBatchId, 'Should have found mutation after ' + nextBatchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\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 var path = decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\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 var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\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 if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = indexeddb_schema_DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return persistence_promise_PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(indexeddb_schema_DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = indexeddb_schema_DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, value, control) {\n var userID = key[0], keyPath = key[1], /*batchID*/ _ = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\n\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, indexeddb_schema_DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\nvar indexeddb_query_cache_IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = null;\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n assert(metadata !== null, 'Missing metadata row that should be added by schema migration.');\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.fromTimestamp(new timestamp_Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n return persistence_promise_PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n return this.saveQueryData(transaction, queryData).next(function () {\n _this.metadata.targetCount += 1;\n _this.updateMetadataFromQueryData(queryData);\n return _this.saveMetadata(transaction);\n });\n };\n IndexedDbQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n var _this = this;\n return this.saveQueryData(transaction, queryData).next(function () {\n if (_this.updateMetadataFromQueryData(queryData)) {\n return _this.saveMetadata(transaction);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n var _this = this;\n assert(this.metadata.targetCount > 0, 'Removing from an empty query cache');\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId)\n .next(function () { return targetsStore(transaction).delete(queryData.targetId); })\n .next(function () {\n _this.metadata.targetCount -= 1;\n return _this.saveMetadata(transaction);\n });\n };\n IndexedDbQueryCache.prototype.saveMetadata = function (transaction) {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.saveQueryData = function (transaction, queryData) {\n return targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n };\n /**\n * Updates the in-memory version of the metadata to account for values in the\n * given QueryData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n IndexedDbQueryCache.prototype.updateMetadataFromQueryData = function (queryData) {\n var needsUpdate = false;\n if (queryData.targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = queryData.targetId;\n needsUpdate = true;\n }\n // TODO(GC): add sequence number check\n return needsUpdate;\n };\n Object.defineProperty(IndexedDbQueryCache.prototype, \"count\", {\n get: function () {\n return this.metadata.targetCount;\n },\n enumerable: true,\n configurable: true\n });\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\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 efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.isEqual(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = decode(key[1]);\n var docKey = new document_key_DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return indexeddb_query_cache_getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction indexeddb_query_cache_getStore(txn, store) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\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 var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof simple_db_SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_serializer.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/** Serializer for values stored in the LocalStore. */\nvar local_serializer_LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = document_key_DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new timestamp_Timestamp(readTime.seconds, readTime.nanos);\n return new document_NoDocument(key, snapshot_version_SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof document_Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = timestamp_Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new mutation_batch_MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new timestamp_Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = snapshot_version_SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new query_data_QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/indexeddb_persistence.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\nvar indexeddb_persistence_LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar indexeddb_persistence_IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new local_serializer_LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new error_FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return simple_db_SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return indexeddb_mutation_queue_IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new indexeddb_query_cache_IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new indexeddb_remote_document_cache_IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n debug(indexeddb_persistence_LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return simple_db_SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n debug(indexeddb_persistence_LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n debug(indexeddb_persistence_LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new error_FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n debug(indexeddb_persistence_LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new error_FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return persistence_promise_PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log_error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log_error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n debug(indexeddb_persistence_LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error('Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log_error('Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return misc_AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\n\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_documents_view.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\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 */\nvar local_documents_view_LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\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 */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new document_NoDocument(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (document_key_DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new document_key_DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof document_Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof document_Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof document_Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof document_NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return persistence_promise_PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\n\n\n//# sourceMappingURL=local_documents_view.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n/**\n * Copyright 2017 Google Inc.\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\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 * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar remote_document_change_buffer_RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\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 * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return persistence_promise_PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return persistence_promise_PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\n\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/local_store.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\nvar local_store_LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar local_store_LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new reference_set_ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new local_documents_view_LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\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 LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new local_documents_view_LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return persistence_promise_PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = timestamp_Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge 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 */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\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 */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update 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 */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new remote_document_change_buffer_RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.updateQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.isEqual(snapshot_version_SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n debug(local_store_LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\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 var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.isEqual(snapshot_version_SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return persistence_promise_PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return persistence_promise_PersistencePromise.waitFor(promises);\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 */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return persistence_promise_PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new query_data_QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new remote_document_change_buffer_RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return persistence_promise_PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return persistence_promise_PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = persistence_promise_PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\n\n\n//# sourceMappingURL=local_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_mutation_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\nvar memory_mutation_queue_MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\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.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new sorted_set_SortedSet(reference_set_DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new mutation_batch_MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new reference_set_DocReference(mutation.key, batchId));\n }\n return persistence_promise_PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return persistence_promise_PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, this.highestAcknowledgedBatchId) + 1;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(nextBatchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return persistence_promise_PersistencePromise.resolve(batch);\n }\n }\n return persistence_promise_PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return persistence_promise_PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new reference_set_DocReference(documentKey, 0);\n var end = new reference_set_DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.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 var startPath = prefix;\n if (!document_key_DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new reference_set_DocReference(new document_key_DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new sorted_set_SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\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 if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\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 var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return persistence_promise_PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new reference_set_DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new reference_set_DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return persistence_promise_PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return persistence_promise_PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\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 */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return 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 */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\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 var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\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 */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\n\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_query_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar memory_query_cache_MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new obj_map_ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = snapshot_version_SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new reference_set_ReferenceSet();\n this.targetCount = 0;\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.saveQueryData = function (queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n // TODO(GC): track sequence number\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n assert(!this.queries.has(queryData.query), 'Adding a query that already exists');\n this.saveQueryData(queryData);\n this.targetCount += 1;\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n assert(this.queries.has(queryData.query), 'Updating a non-existent query');\n this.saveQueryData(queryData);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\n assert(this.queries.has(queryData.query), 'Removing a non-existent target from the cache');\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n this.targetCount -= 1;\n return persistence_promise_PersistencePromise.resolve();\n };\n Object.defineProperty(MemoryQueryCache.prototype, \"count\", {\n get: function () {\n return this.targetCount;\n },\n enumerable: true,\n configurable: true\n });\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return persistence_promise_PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return persistence_promise_PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\n\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar memory_remote_document_cache_MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return persistence_promise_PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return persistence_promise_PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\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 var prefix = new document_key_DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof document_Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return persistence_promise_PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\n\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/memory_persistence.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar memory_persistence_LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar memory_persistence_MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new memory_remote_document_cache_MemoryRemoteDocumentCache();\n this.queryCache = new memory_query_cache_MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // No durable state to read on startup.\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n return [2 /*return*/];\n });\n });\n };\n MemoryPersistence.prototype.shutdown = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return [2 /*return*/];\n });\n });\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new memory_mutation_queue_MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(memory_persistence_LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\n\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar no_op_garbage_collector_NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return persistence_promise_PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\n\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/promise.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\n\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nfunction sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_queue.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nvar TimerId;\n(function (TimerId) {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n TimerId[\"All\"] = \"all\";\n /**\n * The following 4 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed.\n */\n TimerId[\"ListenStreamIdle\"] = \"listen_stream_idle\";\n TimerId[\"ListenStreamConnectionBackoff\"] = \"listen_stream_connection_backoff\";\n TimerId[\"WriteStreamIdle\"] = \"write_stream_idle\";\n TimerId[\"WriteStreamConnectionBackoff\"] = \"write_stream_connection_backoff\";\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n TimerId[\"OnlineStateTimeout\"] = \"online_state_timeout\";\n})(TimerId || (TimerId = {}));\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 */\nvar async_queue_DelayedOperation = /** @class */ (function () {\n function DelayedOperation(asyncQueue, timerId, targetTimeMs, op, removalCallback) {\n this.asyncQueue = asyncQueue;\n this.timerId = timerId;\n this.targetTimeMs = targetTimeMs;\n this.op = op;\n this.removalCallback = removalCallback;\n this.deferred = new Deferred();\n this.then = this.deferred.promise.then.bind(this.deferred.promise);\n this.catch = this.deferred.promise.catch.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(function (err) { });\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 */\n DelayedOperation.createAndSchedule = function (asyncQueue, timerId, delayMs, op, removalCallback) {\n var targetTime = Date.now() + delayMs;\n var delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);\n delayedOp.start(delayMs);\n return delayedOp;\n };\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n DelayedOperation.prototype.start = function (delayMs) {\n var _this = this;\n this.timerHandle = setTimeout(function () { return _this.handleDelayElapsed(); }, delayMs);\n };\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n DelayedOperation.prototype.skipDelay = function () {\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 */\n DelayedOperation.prototype.cancel = function (reason) {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(new error_FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));\n }\n };\n DelayedOperation.prototype.handleDelayElapsed = function () {\n var _this = this;\n this.asyncQueue.enqueue(function () {\n if (_this.timerHandle !== null) {\n _this.clearTimeout();\n return _this.op().then(function (result) {\n return _this.deferred.resolve(result);\n });\n }\n else {\n return Promise.resolve();\n }\n });\n };\n DelayedOperation.prototype.clearTimeout = function () {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n };\n return DelayedOperation;\n}());\nvar async_queue_AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.delayedOperations = [];\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n AsyncQueue.prototype.enqueue = function (op) {\n var _this = this;\n this.verifyNotFailed();\n var newTail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n var message = error.stack || error.message || '';\n log_error('INTERNAL UNHANDLED ERROR: ', message);\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(function () {\n throw error;\n }, 0);\n }\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 error;\n })\n .then(function (result) {\n _this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n };\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\n * the operation prior to its running.\n */\n AsyncQueue.prototype.enqueueAfterDelay = function (timerId, delayMs, op) {\n var _this = this;\n this.verifyNotFailed();\n // While not necessarily harmful, we currently don't expect to have multiple\n // ops with the same timer id in the queue, so defensively reject them.\n assert(!this.containsDelayedOperation(timerId), \"Attempted to schedule multiple operations with timer id \" + timerId + \".\");\n var delayedOp = async_queue_DelayedOperation.createAndSchedule(this, timerId, delayMs, op, function (op) { return _this.removeDelayedOperation(op); });\n this.delayedOperations.push(delayedOp);\n return delayedOp;\n };\n AsyncQueue.prototype.verifyNotFailed = function () {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message));\n }\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n AsyncQueue.prototype.drain = function () {\n return this.enqueue(function () { return Promise.resolve(); });\n };\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n AsyncQueue.prototype.containsDelayedOperation = function (timerId) {\n return this.delayedOperations.findIndex(function (op) { return op.timerId === timerId; }) >= 0;\n };\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId Delayed operations up to and including this TimerId will\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\n * all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n AsyncQueue.prototype.runDelayedOperationsEarly = function (lastTimerId) {\n var _this = this;\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(function () {\n assert(lastTimerId === TimerId.All ||\n _this.containsDelayedOperation(lastTimerId), \"Attempted to drain to missing operation \" + lastTimerId);\n // Run ops in the same order they'd run if they ran naturally.\n _this.delayedOperations.sort(function (a, b) { return a.targetTimeMs - b.targetTimeMs; });\n for (var _i = 0, _a = _this.delayedOperations; _i < _a.length; _i++) {\n var op = _a[_i];\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n return _this.drain();\n });\n };\n /** Called once a DelayedOperation is run or canceled. */\n AsyncQueue.prototype.removeDelayedOperation = function (op) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n var index = this.delayedOperations.indexOf(op);\n assert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n };\n return AsyncQueue;\n}());\n\n\n//# sourceMappingURL=async_queue.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/backoff.js\n/**\n * Copyright 2017 Google Inc.\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\nvar backoff_LOG_TAG = 'ExponentialBackoff';\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 */\nvar backoff_ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n queue, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n timerId, \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 initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \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 */\n maxDelayMs) {\n this.queue = queue;\n this.timerId = timerId;\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n this.timerPromise = null;\n 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 */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\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 */\n ExponentialBackoff.prototype.backoffAndRun = function (op) {\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 var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n debug(backoff_LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, delayWithJitterMs, op);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n };\n ExponentialBackoff.prototype.cancel = function () {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\n\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/persistent_stream.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\nvar persistent_stream_LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\n/** The time a stream stays open after it is marked idle. */\nvar IDLE_TIMEOUT_MS = 60 * 1000;\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 *\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\n * onClose 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 */\nvar persistent_stream_PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connectionTimerId, idleTimerId, connection, credentialsProvider) {\n this.queue = queue;\n this.idleTimerId = idleTimerId;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.inactivityTimerPromise = null;\n this.stream = null;\n this.listener = null;\n this.backoff = new backoff_ExponentialBackoff(queue, connectionTimerId, BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\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 */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\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 ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function (listener) {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff(listener);\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.listener = listener;\n this.auth();\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 */\n PersistentStream.prototype.stop = function () {\n if (this.isStarted()) {\n this.close(PersistentStreamState.Stopped);\n }\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 function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.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 */\n PersistentStream.prototype.markIdle = function () {\n var _this = this;\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 if (this.isOpen() && this.inactivityTimerPromise === null) {\n this.inactivityTimerPromise = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, function () { return _this.handleIdleCloseTimer(); });\n }\n };\n /** Sends a message to the underlying stream. */\n PersistentStream.prototype.sendRequest = function (msg) {\n this.cancelIdleCheck();\n this.stream.send(msg);\n };\n /** Called by the idle timer when the stream should close due to inactivity. */\n PersistentStream.prototype.handleIdleCloseTimer = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (this.isOpen()) {\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 [2 /*return*/, this.close(PersistentStreamState.Initial)];\n }\n return [2 /*return*/];\n });\n });\n };\n /** Marks the stream as active again. */\n PersistentStream.prototype.cancelIdleCheck = function () {\n if (this.inactivityTimerPromise) {\n this.inactivityTimerPromise.cancel();\n this.inactivityTimerPromise = null;\n }\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` unless `finalState` is set to\n * `PersistentStreamState.Stopped`.\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */\n PersistentStream.prototype.close = function (finalState, error) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var listener;\n return tslib_es6[\"__generator\"](this, function (_a) {\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error), \"Can't provide an error when not in an error state.\");\n // The stream will be closed so we don't need our idle close timer anymore.\n this.cancelIdleCheck();\n // Ensure we don't leave a pending backoff operation queued (in case close()\n // was called while we were waiting to reconnect).\n this.backoff.cancel();\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n }\n else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log_error(error.toString());\n log_error('Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\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 = finalState;\n listener = this.listener;\n // Clear the listener to avoid bleeding of events from the underlying streams.\n this.listener = null;\n // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it\n // could trigger undesirable recovery logic, etc.).\n if (finalState !== PersistentStreamState.Stopped) {\n return [2 /*return*/, listener.onClose(error)];\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n PersistentStream.prototype.tearDown = function () { };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\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.startStream(token);\n }, function (error) {\n _this.queue.enqueue(function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () {\n var rpcError;\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (this.state !== PersistentStreamState.Stopped) {\n rpcError = new error_FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return [2 /*return*/, this.handleStreamClose(rpcError)];\n }\n return [2 /*return*/];\n });\n }); });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfStillActive = function (stream, fn) {\n _this.queue.enqueue(function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // Only raise events if the stream instance has not changed\n if (this.stream === stream) {\n return [2 /*return*/, fn()];\n }\n return [2 /*return*/];\n });\n }); });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n var currentStream_1 = this.startRpc(token);\n this.stream = currentStream_1;\n this.stream.onOpen(function () {\n dispatchIfStillActive(currentStream_1, function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function (listener) {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndRun(function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (this.state === PersistentStreamState.Stopped) {\n // We should have canceled the backoff timer when the stream was\n // closed, but just in case we make this a no-op.\n return [2 /*return*/];\n }\n this.state = PersistentStreamState.Initial;\n this.start(listener);\n assert(this.isStarted(), 'PersistentStream should have started');\n return [2 /*return*/];\n });\n }); });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n debug(persistent_stream_LOG_TAG, \"close with error: \" + error);\n this.stream = null;\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 this.close(PersistentStreamState.Error, error);\n };\n return PersistentStream;\n}());\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar persistent_stream_PersistentListenStream = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](PersistentListenStream, _super);\n function PersistentListenStream(queue, connection, credentials, serializer) {\n var _this = _super.call(this, queue, TimerId.ListenStreamConnectionBackoff, TimerId.ListenStreamIdle, connection, credentials) || this;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.sendRequest(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n };\n return PersistentListenStream;\n}(persistent_stream_PersistentStream));\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 */\nvar persistent_stream_PersistentWriteStream = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](PersistentWriteStream, _super);\n function PersistentWriteStream(queue, connection, credentials, serializer) {\n var _this = _super.call(this, queue, TimerId.WriteStreamConnectionBackoff, TimerId.WriteStreamIdle, connection, credentials) || this;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function (listener) {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this, listener);\n };\n PersistentWriteStream.prototype.tearDown = function () {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\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.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\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 */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\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 var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.sendRequest(request);\n };\n return PersistentWriteStream;\n}(persistent_stream_PersistentStream));\n\n\n//# sourceMappingURL=persistent_stream.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/datastore.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar datastore_Datastore = /** @class */ (function () {\n function Datastore(queue, connection, credentials, serializer) {\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n }\n Datastore.prototype.newPersistentWriteStream = function () {\n return new persistent_stream_PersistentWriteStream(this.queue, this.connection, this.credentials, this.serializer);\n };\n Datastore.prototype.newPersistentWatchStream = function () {\n return new persistent_stream_PersistentListenStream(this.queue, this.connection, this.credentials, this.serializer);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('Commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeRPC(rpcName, request, token);\n });\n };\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\n });\n };\n return Datastore;\n}());\n\n\n//# sourceMappingURL=datastore.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/transaction.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar transaction_Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof document_NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = snapshot_version_SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new error_FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\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 */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return mutation_Precondition.updateTime(version);\n }\n else {\n return mutation_Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.isEqual(snapshot_version_SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return mutation_Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return mutation_Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new mutation_DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, snapshot_version_SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\n\n\n//# sourceMappingURL=transaction.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/online_state_tracker.js\n/**\n * Copyright 2018 Google Inc.\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\n\n\nvar online_state_tracker_LOG_TAG = 'OnlineStateTracker';\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\nvar MAX_WATCH_STREAM_FAILURES = 2;\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nvar ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\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 */\nvar online_state_tracker_OnlineStateTracker = /** @class */ (function () {\n function OnlineStateTracker(asyncQueue, onlineStateHandler) {\n this.asyncQueue = asyncQueue;\n this.onlineStateHandler = onlineStateHandler;\n /** The current OnlineState. */\n this.state = 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.watchStreamFailures = 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.onlineStateTimer = 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.shouldWarnClientIsOffline = true;\n }\n /**\n * Called by RemoteStore when a watch stream is started.\n *\n * It sets the OnlineState to Unknown and starts the onlineStateTimer\n * if necessary.\n */\n OnlineStateTracker.prototype.handleWatchStreamStart = function () {\n var _this = this;\n this.setAndBroadcast(OnlineState.Unknown);\n if (this.onlineStateTimer === null) {\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout, ONLINE_STATE_TIMEOUT_MS, function () {\n _this.onlineStateTimer = null;\n assert(_this.state === OnlineState.Unknown, 'Timer should be canceled if we transitioned to a different state.');\n debug(online_state_tracker_LOG_TAG, \"Watch stream didn't reach online or offline within \" +\n (ONLINE_STATE_TIMEOUT_MS + \"ms. Considering client offline.\"));\n _this.logClientOfflineWarningIfNecessary();\n _this.setAndBroadcast(OnlineState.Offline);\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n return Promise.resolve();\n });\n }\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 */\n OnlineStateTracker.prototype.handleWatchStreamFailure = function () {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n this.logClientOfflineWarningIfNecessary();\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\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 */\n OnlineStateTracker.prototype.set = function (newState) {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n this.setAndBroadcast(newState);\n };\n OnlineStateTracker.prototype.setAndBroadcast = function (newState) {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n };\n OnlineStateTracker.prototype.logClientOfflineWarningIfNecessary = function () {\n if (this.shouldWarnClientIsOffline) {\n log_error('Could not reach Firestore backend.');\n this.shouldWarnClientIsOffline = false;\n }\n };\n OnlineStateTracker.prototype.clearOnlineStateTimer = function () {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n };\n return OnlineStateTracker;\n}());\n\n\n//# sourceMappingURL=online_state_tracker.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/remote/remote_store.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar remote_store_LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar remote_store_RemoteStore = /** @class */ (function () {\n function RemoteStore(\n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, asyncQueue, onlineStateHandler) {\n this.localStore = localStore;\n this.datastore = datastore;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\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.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n this.onlineStateTracker = new online_state_tracker_OnlineStateTracker(asyncQueue, onlineStateHandler);\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) === (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Idempotent. */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n if (this.isNetworkEnabled()) {\n return Promise.resolve();\n }\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream();\n this.writeStream = this.datastore.newPersistentWriteStream();\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n else {\n _this.onlineStateTracker.set(OnlineState.Unknown);\n }\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n RemoteStore.prototype.disableNetwork = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n this.disableNetworkInternal();\n // Set the OnlineState to Offline so get()s return from cache, etc.\n this.onlineStateTracker.set(OnlineState.Offline);\n return [2 /*return*/];\n });\n });\n };\n /**\n * Disables the network, if it is currently enabled.\n */\n RemoteStore.prototype.disableNetworkInternal = function () {\n if (this.isNetworkEnabled()) {\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n }\n };\n RemoteStore.prototype.shutdown = function () {\n debug(remote_store_LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetworkInternal();\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.onlineStateTracker.set(OnlineState.Unknown);\n return Promise.resolve();\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n if (isEmpty(this.listenTargets)) {\n this.watchStream.markIdle();\n }\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 */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\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 */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n this.onlineStateTracker.handleWatchStreamStart();\n };\n /**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n return tslib_es6[\"__generator\"](this, function (_a) {\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n this.onlineStateTracker.handleWatchStreamFailure();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.startWatchStream();\n }\n else {\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var changes;\n return tslib_es6[\"__generator\"](this, function (_a) {\n // Mark the client as online since we got a message from the server\n this.onlineStateTracker.set(OnlineState.Online);\n if (watchChange instanceof watch_change_WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return [2 /*return*/, this.handleTargetError(watchChange)];\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.isEqual(snapshot_version_SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return [2 /*return*/, this.handleWatchChangeBatch(snapshotVersion, changes)];\n }\n return [2 /*return*/];\n });\n });\n };\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 RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new watch_change_WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new document_key_DocumentKey(query.path);\n var deletedDoc = new document_NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new query_data_QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new query_data_QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // A watched target might have been removed already.\n if (contains(this.listenTargets, targetId)) {\n delete this.listenTargets[targetId];\n return [2 /*return*/, this.syncEngine.rejectListen(targetId, error)];\n }\n return [2 /*return*/];\n });\n }); });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n debug(remote_store_LOG_TAG, 'Stopping write stream with ' +\n this.pendingWrites.length +\n ' pending writes');\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (this.canWriteMutations()) {\n return [2 /*return*/, this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n if (_this.pendingWrites.length === 0) {\n _this.writeStream.markIdle();\n }\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n })];\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n this.writeStream.writeHandshake();\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = mutation_batch_MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n var errorHandling;\n return tslib_es6[\"__generator\"](this, function (_a) {\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return [2 /*return*/, errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n })];\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n debug(remote_store_LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return [2 /*return*/, this.localStore.setLastStreamToken(emptyByteString())];\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n var batch;\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (isPermanentError(error.code)) {\n batch = this.pendingWrites.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 this.writeStream.inhibitBackoff();\n return [2 /*return*/, this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n })];\n }\n else {\n // Transient error, just let the retry logic kick in.\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.createTransaction = function () {\n return new transaction_Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n debug(remote_store_LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // If the network has been explicitly disabled, make sure we don't\n // accidentally re-enable it.\n if (this.isNetworkEnabled()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n return this.enableNetwork();\n }\n };\n return RemoteStore;\n}());\n\n\n//# sourceMappingURL=remote_store.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/core/firestore_client.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\nvar firestore_client_LOG_TAG = 'FirestoreClient';\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 */\nvar firestore_client_FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \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 asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.enqueue(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.enqueue(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.enqueue(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new no_op_garbage_collector_NoOpGarbageCollector();\n var storagePrefix = indexeddb_persistence_IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new serializer_JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new indexeddb_persistence_IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new eager_garbage_collector_EagerGarbageCollector();\n this.persistence = new memory_persistence_MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new local_store_LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new datastore_Datastore(_this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.syncEngine.applyOnlineStateChange(onlineState);\n _this.eventMgr.applyOnlineStateChange(onlineState);\n };\n _this.remoteStore = new remote_store_RemoteStore(_this.localStore, datastore, _this.asyncQueue, onlineStateChangedHandler);\n _this.syncEngine = new sync_engine_SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new event_manager_EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(firestore_client_LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.enqueue(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .enqueue(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new event_manager_QueryListener(query, observer, options);\n this.asyncQueue.enqueue(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.enqueue(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.enqueue(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .enqueue(function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () { return tslib_es6[\"__generator\"](this, function (_a) {\n return [2 /*return*/];\n }); }); })\n .then(function () { return _this.syncEngine.runTransaction(updateFunction); });\n };\n return FirestoreClient;\n}());\n\n\n//# sourceMappingURL=firestore_client.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/util/async_observer.js\n/**\n * Copyright 2017 Google Inc.\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 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 */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\n\n\n//# sourceMappingURL=async_observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/auth/user.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isAuthenticated = function () {\n return this.uid != null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n }\n else {\n return 'anonymous-user';\n }\n };\n User.prototype.isEqual = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\n\n\n//# sourceMappingURL=user.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/credentials.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\n\n/** A CredentialsProvider that always yields an empty token. */\nvar credentials_EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\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.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\n\nvar credentials_FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.isEqual(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new error_FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\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 * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar credentials_FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\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 */\nvar credentials_FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new credentials_FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nfunction makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new credentials_EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'gapi':\n return new credentials_FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/observer.js\n/**\n * Copyright 2017 Google Inc.\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 isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/field_value.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return field_value_DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return field_value_ServerTimestampFieldValueImpl.instance;\n };\n FieldValueImpl.prototype.isEqual = function (other) {\n return this === other;\n };\n return FieldValueImpl;\n}());\n\nvar field_value_DeleteFieldValueImpl = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\n\nvar field_value_ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/user_data_converter.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar user_data_converter_ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new mutation_PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new mutation_SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar user_data_converter_ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new mutation_PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new mutation_TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar user_data_converter_ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * 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 function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar user_data_converter_UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call. */\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.Set, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new user_data_converter_ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.MergeSet, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new mutation_FieldMask(context.fieldMask);\n return new user_data_converter_ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof field_value_DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new user_data_converter_ParseContext(UserDataSource.Update, methodName, path_FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = field_value_ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof field_value_DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new mutation_FieldMask(fieldMaskPaths);\n return new user_data_converter_ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new user_data_converter_ParseContext(UserDataSource.QueryValue, methodName, path_FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\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 * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = field_value_NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new field_value_ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new SortedMap(primitiveComparator);\n forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new field_value_ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return field_value_NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (isSafeInteger(value)) {\n return new field_value_IntegerValue(value);\n }\n else {\n return new field_value_DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return field_value_BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new field_value_StringValue(value);\n }\n else if (value instanceof Date) {\n return new field_value_TimestampValue(timestamp_Timestamp.fromDate(value));\n }\n else if (value instanceof geo_point_GeoPoint) {\n return new field_value_GeoPointValue(value);\n }\n else if (value instanceof blob_Blob) {\n return new field_value_BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new field_value_RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof field_value_DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof field_value_ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\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 */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof geo_point_GeoPoint) &&\n !(input instanceof blob_Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nfunction fieldPathFromArgument(methodName, path) {\n if (path instanceof field_path_FieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\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 split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/api/database.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar database_FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.isEqual = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar database_Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n // Public for use in tests.\n // TODO(mikelehen): Use modularized initialization instead.\n this._queue = new async_queue_AsyncQueue();\n this.INTERNAL = {\n delete: function () { return tslib_es6[\"__awaiter\"](_this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (this._firestoreClient) {\n return [2 /*return*/, this._firestoreClient.shutdown()];\n }\n return [2 /*return*/];\n });\n }); }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new credentials_FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new database_info_DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new credentials_EmptyCredentialsProvider();\n }\n config.settings = new database_FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (contains(settingsLiteral, 'persistence')) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new database_FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.enableNetwork();\n };\n Firestore.prototype.disableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.disableNetwork();\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof database_DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new user_data_converter_UserDataConverter(preConverter);\n this._firestoreClient = new firestore_client_FirestoreClient(platform_PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (contains(options, 'firestoreId')) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new database_info_DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new database_CollectionReference(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return database_DocumentReference.forPath(path_ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new database_Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new database_WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n setLogLevel(LogLevel.DEBUG);\n break;\n case 'error':\n setLogLevel(LogLevel.ERROR);\n break;\n case 'silent':\n setLogLevel(LogLevel.SILENT);\n break;\n default:\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\n\n/**\n * A reference to a transaction.\n */\nvar database_Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof document_NoDocument) {\n return new database_DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new database_DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\n\nvar database_WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, mutation_Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new mutation_DeleteMutation(ref._key, mutation_Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return [2 /*return*/, this._firestore.ensureClientConfigured().write(this._mutations)];\n }\n return [2 /*return*/];\n });\n });\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new error_FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar database_DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new document_key_DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new database_CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = path_ResourcePath.fromString(pathString);\n return new database_CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.isEqual(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof field_path_FieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, mutation_Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new mutation_DeleteMutation(this._key, mutation_Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new database_DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(query_Query.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.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 reject(new error_FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\n\nvar SnapshotMetadata = /** @class */ (function () {\n function SnapshotMetadata(hasPendingWrites, fromCache) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n SnapshotMetadata.prototype.isEqual = function (other) {\n return (this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache);\n };\n return SnapshotMetadata;\n}());\nvar database_DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function (options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n return !this._document\n ? undefined\n : this.convertObject(this._document.data, field_value_FieldValueOptions.fromSnapshotOptions(options));\n };\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== undefined) {\n return this.convertValue(value, field_value_FieldValueOptions.fromSnapshotOptions(options));\n }\n }\n return undefined;\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new database_DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return new SnapshotMetadata(this._document !== null && this._document.hasLocalMutations, this._fromCache);\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)));\n };\n DocumentSnapshot.prototype.convertObject = function (data, options) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value, options);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value, options) {\n if (value instanceof field_value_ObjectValue) {\n return this.convertObject(value, options);\n }\n else if (value instanceof field_value_ArrayValue) {\n return this.convertArray(value, options);\n }\n else if (value instanceof field_value_RefValue) {\n var key = value.value(options);\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log_error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new database_DocumentReference(key, this._firestore);\n }\n else {\n return value.value(options);\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data, options) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value, options);\n });\n };\n return DocumentSnapshot;\n}());\n\nvar database_QueryDocumentSnapshot = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](QueryDocumentSnapshot, _super);\n function QueryDocumentSnapshot(firestore, key, document, fromCache) {\n return _super.call(this, firestore, key, document, fromCache) || this;\n }\n QueryDocumentSnapshot.prototype.data = function (options) {\n var data = _super.prototype.data.call(this, options);\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\n return data;\n };\n return QueryDocumentSnapshot;\n}(database_DocumentSnapshot));\n\nvar database_Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new path_ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new field_value_RefValue(this.firestore._databaseId, new document_key_DocumentKey(path));\n }\n else if (value instanceof database_DocumentReference) {\n var ref = value;\n fieldValue = new field_value_RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, query_RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new query_OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof database_DocumentSnapshot) {\n if (fields.length > 0) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new error_FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\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.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\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 (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new field_value_RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new query_Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new document_key_DocumentKey(this._query.path.child(rawValue));\n components.push(new field_value_RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new query_Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new database_QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof query_RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.isEqual(inequality)) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\n\nvar database_QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new database_Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n /** Check the equality. The call can be very expensive. */\n QuerySnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot));\n };\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new database_QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\n\nvar database_CollectionReference = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, query_Query.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new database_DocumentReference(new document_key_DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = misc_AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = path_ResourcePath.fromString(pathString);\n return database_DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(database_Query));\n\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateSnapshotOptions(methodName, options) {\n if (options === undefined) {\n return {};\n }\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof database_DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new error_FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nfunction changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new database_QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nvar PublicFirestore = makeConstructorPrivate(database_Firestore, 'Use firebase.firestore() instead.');\nvar PublicTransaction = makeConstructorPrivate(database_Transaction, 'Use firebase.firestore().runTransaction() instead.');\nvar PublicWriteBatch = makeConstructorPrivate(database_WriteBatch, 'Use firebase.firestore().batch() instead.');\nvar PublicDocumentReference = makeConstructorPrivate(database_DocumentReference, 'Use firebase.firestore().doc() instead.');\nvar PublicDocumentSnapshot = makeConstructorPrivate(database_DocumentSnapshot);\nvar PublicQueryDocumentSnapshot = makeConstructorPrivate(database_QueryDocumentSnapshot);\nvar PublicQuery = makeConstructorPrivate(database_Query);\nvar PublicQuerySnapshot = makeConstructorPrivate(database_QuerySnapshot);\nvar PublicCollectionReference = makeConstructorPrivate(database_CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/src/platform/config.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: geo_point_GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: field_path_FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: database_Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nfunction configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new database_Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nfunction configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = database_Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n// CONCATENATED MODULE: ../firestore/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerFirestore\"] = registerFirestore;\n/**\n * Copyright 2017 Google Inc.\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\n\nfunction registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n\n/***/ 117:\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function ea(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var p=\"closure_uid_\"+(1E9*Math.random()>>>0),fa=0;function ha(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ia(a,b,c){if(!a)throw Error();if(2b?null:l(a)?a.charAt(b):a[b]}function ua(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function va(a){return Array.prototype.concat.apply([],arguments)}function wa(a){var b=a.length;if(0b?1:0};var w;a:{var Aa=k.navigator;if(Aa){var Ba=Aa.userAgent;if(Ba){w=Ba;break a}}w=\"\"}function x(a){return-1!=w.indexOf(a)};function Ca(a,b,c){for(var d in a)b.call(c,a[d],d,a)}function Da(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Ea(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b}function Fa(a){var b={},c;for(c in a)b[c]=a[c];return b}var Ga=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");\nfunction Ha(a,b){for(var c,d,e=1;eparseFloat(Sa)){Ra=String(Ua);break a}}Ra=Sa}var Ka={};\nfunction Va(a){return Ja(a,function(){for(var b=0,c=ya(String(Ra)).split(\".\"),d=ya(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var db=\"closure_listenable_\"+(1E6*Math.random()|0),eb=0;function fb(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ga=e;this.key=++eb;this.Z=this.ba=!1}function gb(a){a.Z=!0;a.listener=null;a.proxy=null;a.src=null;a.ga=null};function hb(a){this.src=a;this.a={};this.b=0}hb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=ib(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=xb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function pb(a){if(da(a))return a;a[zb]||(a[zb]=function(b){return a.handleEvent(b)});return a[zb]};function A(){u.call(this);this.f=new hb(this);this.N=this;this.J=null}t(A,u);A.prototype[db]=!0;g=A.prototype;g.addEventListener=function(a,b,c,d){nb(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){vb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.J;if(c)for(b=[];c;c=c.J)b.push(c);c=this.N;var d=a.type||a;if(l(a))a=new z(a,c);else if(a instanceof z)a.target=a.target||c;else{var e=a;a=new z(d,c);Ha(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Ab(h,d,!0,a)&&e}h=a.a=c;e=Ab(h,d,!0,a)&&e;e=Ab(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a)}Wb=!1};function Xb(a,b){A.call(this);this.b=a||1;this.a=b||k;this.c=q(this.lb,this);this.g=r()}t(Xb,A);g=Xb.prototype;g.ea=!1;g.O=null;g.lb=function(){if(this.ea){var a=r()-this.g;0=nc(this).value)for(da(b)&&(b=b()),a=new fc(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};\nvar oc={},pc=null;function qc(a){pc||(pc=new hc(\"\"),oc[\"\"]=pc,pc.c=lc);var b;if(!(b=oc[a])){b=new hc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=qc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;oc[a]=b}return b};function C(a,b){a&&a.log(jc,b,void 0)}function rc(a,b){a&&a.log(kc,b,void 0)}function D(a,b){a&&a.log(mc,b,void 0)};function sc(){this.a=qc(\"goog.labs.net.webChannel.WebChannelDebug\");this.b=!0}sc.prototype.Ea=function(){this.b=!1};function tc(a,b,c,d,e,f){E(a,function(){if(a.b)if(f){var h=\"\";for(var m=f.split(\"&\"),v=0;ve.length)){var f=e[1];if(n(f)&&!(1>f.length)){var h=f[0];if(\"noop\"!=h&&\"stop\"!=h&&\"close\"!=h)for(var m=1;mb||3==b&&!Na&&!a.a.V())){a.B||4!=b||7==c||(8==c||0>=d?zc(3):zc(2));ad(a);var e=a.a.W();a.C=e;(c=a.a.V())||G(a.b,function(){return\"No response text for uri \"+a.g+\" status \"+e});a.f=200==e;uc(a.b,a.o,a.g,a.c,a.T,b,e);if(a.f){if(d=bd(a))F(a.b,a.c,d,\"Initial handshake response via X-HTTP-Initial-Response\"),a.v=!0,cd(a,d);a.K?(dd(a,b,c),Na&&a.f&&3==b&&ed(a)):(F(a.b,a.c,c,null),cd(a,c));4==b&&fd(a);a.f&&!a.B&&(4==b?a.i.ta(a):(a.f=!1,Yc(a)))}else 400==\ne&&0b.length)return Tc;b=b.substr(d,c);a.G=d+c;return b}g.cancel=function(){this.B=!0;fd(this)};function Yc(a){a.U=r()+a.R;jd(a,a.R)}function jd(a,b){if(null!=a.s)throw Error(\"WatchDog timer not null\");a.s=Dc(q(a.gb,a),b)}function ad(a){a.s&&(k.clearTimeout(a.s),a.s=null)}\ng.gb=function(){this.s=null;var a=r();0<=a-this.U?(this.f&&H(this.b,\"Received watchdog timeout even though request loaded successfully\"),wc(this.b,this.g),2!=this.J&&(zc(3),K(17)),fd(this),this.m=2,gd(this)):(C(this.b.a,\"WatchDog timer called too early\"),jd(this,this.U-a))};function gd(a){a.i.Ka()||a.B||a.i.ta(a)}function fd(a){ad(a);var b=a.I;b&&\"function\"==typeof b.$&&b.$();a.I=null;Yb(a.S);ec(a.L);a.a&&(b=a.a,a.a=null,b.abort(),b.$())}\nfunction cd(a,b){try{a.i.Na(a,b),zc(4)}catch(c){xc(a.b,c,\"Error in httprequest callback\")}};function kd(a){if(a.A&&\"function\"==typeof a.A)return a.A();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&md(a),!0):!1}function md(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function ud(a,b,c){b instanceof xd?(a.c=b,Dd(a.c,a.h)):(c||(b=yd(b,Ed)),a.c=new xd(b,a.h))}\nfunction R(a,b,c){a.c.set(b,c)}function Zc(a,b,c){n(c)||(c=[String(c)]);Fd(a.c,b,c)}function Vc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^r()).toString(36));return a}function Gd(a){return a instanceof Q?M(a):new Q(a,void 0)}function Hd(a,b,c,d){var e=new Q(null,void 0);a&&rd(e,a);b&&sd(e,b);c&&td(e,c);d&&(e.a=d);return e}function wd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction yd(a,b,c){return l(a)?(a=encodeURI(a).replace(b,Id),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Id(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var zd=/[#\\/\\?@]/g,Bd=/[#\\?:]/g,Ad=/[#\\?]/g,Ed=/[#\\?@]/g,Cd=/#/g;function xd(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function S(a){a.a||(a.a=new O,a.b=0,a.c&&qd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=xd.prototype;\ng.add=function(a,b){S(this);this.c=null;a=Jd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Kd(a,b){S(a);b=Jd(a,b);P(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,od(a.a,b))}function Ld(a,b){S(a);b=Jd(a,b);return P(a.a.b,b)}g.forEach=function(a,b){S(this);this.a.forEach(function(c,d){ra(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.M=function(){S(this);for(var a=this.a.A(),b=this.a.M(),c=[],d=0;d=a.f:!1}function de(a,b){a.b?a=a.b==b:a.a?(b=Xd(b),a=P(a.a.a.b,b)):a=!1;return a}function be(a,b){a.a?a.a.add(b):a.b=b}\nfunction ee(a,b){if(a.b&&a.b==b)a.b=null;else{var c;if(c=a.a)c=Xd(b),c=P(a.a.a.b,c);c&&od(a.a.a,Xd(b))}}Zd.prototype.cancel=function(){this.c=fe(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ra(this.a.A(),function(a){a.cancel()}),nd(this.a.a))};function fe(a){if(null!=a.b)return a.c.concat(a.b.u);if(null!=a.a&&0!=a.a.a.c){var b=a.c;ra(a.a.A(),function(a){b=b.concat(a.u)});return b}return wa(a.c)}function ge(a,b){a.c=a.c.concat(b)};function he(){}he.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};he.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function ie(){this.a=new he}function je(a,b,c){var d=c||\"\";try{ld(a,function(a,c){var e=a;ea(a)&&(e=Db(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function ke(a,b){var c=new sc;G(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ja(le,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ja(le,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ja(le,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ja(le,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function le(a,b,c,d,e){try{G(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){xc(a,f)}};function T(a){A.call(this);this.headers=new O;this.D=a||null;this.c=!1;this.v=this.a=null;this.K=this.u=\"\";this.j=0;this.g=\"\";this.h=this.I=this.s=this.G=!1;this.l=0;this.B=null;this.L=me;this.C=this.o=!1}t(T,A);var me=\"\";T.prototype.b=qc(\"goog.net.XhrIo\");var ne=/^https?$/i,oe=[\"POST\",\"PUT\"];g=T.prototype;\ng.fa=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.u+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.u=a;this.g=\"\";this.j=0;this.K=b;this.G=!1;this.c=!0;this.a=this.D?Pc(this.D):Pc(Nc);this.v=this.D?Lc(this.D):Lc(Nc);this.a.onreadystatechange=q(this.Ma,this);try{D(this.b,U(this,\"Opening Xhr\")),this.I=!0,this.a.open(b,String(a),!0),this.I=!1}catch(f){D(this.b,U(this,\"Error opening Xhr: \"+f.message));pe(this,f);return}a=c||\"\";var e=new O(this.headers);\nd&&ld(d,function(a,b){e.set(b,a)});d=sa(e.M());c=k.FormData&&a instanceof k.FormData;!(0<=qa(oe,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.L&&(this.a.responseType=this.L);\"withCredentials\"in this.a&&this.a.withCredentials!==this.o&&(this.a.withCredentials=this.o);try{qe(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}R(a,b,c);return a};function xe(a){this.xa=0;this.g=[];this.a=new sc;this.I=new Vd;this.X=this.ua=this.D=this.ja=this.b=this.K=this.j=this.U=this.h=this.L=this.i=null;this.Va=this.R=0;this.Ua=a&&a.Eb||!1;this.ka=this.C=this.s=this.l=this.m=this.f=null;this.u=this.wa=this.N=-1;this.T=this.B=this.v=0;this.G=void 0;this.S=a&&a.supportsCrossDomainXhr||!1;this.J=\"\";this.c=new Zd(a&&a.concurrentRequestLimit);this.la=new ie;this.o=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;(this.va=a&&a.fastHandshake||!1)&&\n!this.o&&(C(this.a.a,\"Force backgroundChannelTest when fastHandshake is enabled.\"),this.o=!0);a&&a.Ea&&this.a.Ea()}g=xe.prototype;g.na=8;g.F=1;\nfunction ye(a){G(a.a,\"disconnect()\");ze(a);if(3==a.F){var b=a.R++,c=M(a.D);R(c,\"SID\",a.J);R(c,\"RID\",b);R(c,\"TYPE\",\"terminate\");Ae(a,c);b=new L(a,a.a,b,void 0);b.J=2;b.h=Vc(M(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.h.toString(),\"\"));!c&&k.Image&&((new Image).src=b.h,c=!0);c||(b.a=b.i.ca(null),b.a.fa(b.h));b.D=r();Yc(b)}Be(a)}\nfunction ze(a){a.C&&(a.C.abort(),a.C=null);a.b&&(a.b.cancel(),a.b=null);a.l&&(k.clearTimeout(a.l),a.l=null);Ce(a);a.c.cancel();a.m&&(k.clearTimeout(a.m),a.m=null)}function De(a,b){1E3==a.g.length&&H(a.a,function(){return\"Already have 1000 queued maps upon queueing \"+Db(b)});a.g.push(new Yd(a.Va++,b));3==a.F&&Ee(a)}g.Ka=function(){return 0==this.F};function Ee(a){ce(a.c)||a.m||(a.m=Dc(q(a.Pa,a),0),a.v=0)}\nfunction Fe(a,b){var c=a.c;if((c.b?1:c.a?c.a.a.c:0)>=a.c.f-(a.m?1:0))return H(a.a,\"Unexpected retry request is scheduled.\"),!1;if(a.m)return G(a.a,\"Use the retry request that is already scheduled.\"),a.g=b.u.concat(a.g),!0;if(1==a.F||2==a.F||a.v>=(a.Ua?0:2))return!1;G(a.a,\"Going to retry POST\");a.m=Dc(q(a.Pa,a,b),Ge(a,a.v));a.v++;return!0}\ng.Pa=function(a){this.m=null;G(this.a,\"startForwardChannel_\");if(1==this.F)if(a)H(this.a,\"Not supposed to retry the open\");else{G(this.a,\"open_()\");this.R=Math.floor(1E5*Math.random());a=this.R++;var b=new L(this,this.a,a,void 0),c=this.i;this.L&&(c?(c=Fa(c),Ha(c,this.L)):c=this.L);null===this.h&&(b.j=c);var d=He(this,b),e=M(this.D);R(e,\"RID\",a);R(e,\"CVER\",22);this.o&&this.j&&R(e,\"X-HTTP-Session-Id\",this.j);Ae(this,e);this.h&&c&&we(e,this.h,c);be(this.c,b);this.va?(R(e,\"$req\",d),R(e,\"SID\",\"null\"),\nb.X=!0,Uc(b,e,null)):Uc(b,e,d);this.F=2}else 3==this.F&&(a?Ie(this,a):0==this.g.length?G(this.a,\"startForwardChannel_ returned: nothing to send\"):ce(this.c)?H(this.a,\"startForwardChannel_ returned: connection already in progress\"):(Ie(this),G(this.a,\"startForwardChannel_ finished, sent request\")))};\nfunction Ie(a,b){var c;b?c=b.c:c=a.R++;var d=M(a.D);R(d,\"SID\",a.J);R(d,\"RID\",c);R(d,\"AID\",a.N);Ae(a,d);a.h&&a.i&&we(d,a.h,a.i);c=new L(a,a.a,c,a.v+1);null===a.h&&(c.j=a.i);b&&(a.g=b.u.concat(a.g));b=He(a,c);c.setTimeout(1E4+Math.round(1E4*Math.random()));be(a.c,c);Uc(c,d,b)}function Ae(a,b){a.f&&ld({},function(a,d){R(b,d,a)})}\nfunction He(a,b){var c=Math.min(a.g.length,1E3),d=a.f?q(a.f.Wa,a.f,a):null;a:for(var e=a.g,f=-1;;){var h=[\"count=\"+c];-1==f?0I)f=Math.max(0,e[v].a-100),m=!1;else try{je(W,h,\"req\"+I+\"_\")}catch(Lb){d&&d(W)}}if(m){d=h.join(\"&\");break a}}a=a.g.splice(0,c);b.u=a;return d}function Je(a){if(!a.b&&!a.l){a.T=1;var b=a.Oa;Tb||Ub();Wb||(Tb(),Wb=!0);Pb.add(b,a);a.B=0}}\nfunction Ke(a){if(a.b||a.l)return H(a.a,\"Request already in progress\"),!1;if(3<=a.B)return!1;G(a.a,\"Going to retry GET\");a.T++;a.l=Dc(q(a.Oa,a),Ge(a,a.B));a.B++;return!0}\ng.Oa=function(){this.l=null;G(this.a,\"Creating new HttpRequest\");this.b=new L(this,this.a,\"rpc\",this.T);null===this.h&&(this.b.j=this.i);this.b.N=0;var a=M(this.ua);R(a,\"RID\",\"rpc\");R(a,\"SID\",this.J);R(a,\"CI\",this.ka?\"0\":\"1\");R(a,\"AID\",this.N);Ae(this,a);R(a,\"TYPE\",\"xmlhttp\");this.h&&this.i&&we(a,this.h,this.i);this.G&&this.b.setTimeout(this.G);Xc(this.b,a,!0,this.X);G(this.a,\"New Request created\")};\nfunction Sd(a,b,c){G(a.a,\"Test Connection Finished\");var d=b.l;d&&ae(a.c,d);a.ka=c;a.u=b.f;G(a.a,\"connectChannel_()\");a.D=Le(a,a.ja);Ee(a)}function Ud(a,b){G(a.a,\"Test Connection Failed\");a.u=b.f;V(a,2)}\ng.Na=function(a,b){if(0!=this.F&&(this.b==a||de(this.c,a)))if(this.u=a.C,!a.v&&de(this.c,a)&&3==this.F){try{var c=this.la.a.parse(b)}catch(f){c=null}if(n(c)&&3==c.length)if(b=c,0==b[0])a:if(G(this.a,\"Server claims our backchannel is missing.\"),this.l)G(this.a,\"But we are currently starting the request.\");else{if(this.b)if(this.b.D+3E3b&&this.ka&&0==this.B&&!this.s&&(this.s=Dc(q(this.cb,this),6E3)));else G(this.a,\"Bad POST response data returned\"),V(this,11)}else if((a.v||this.b==a)&&Ce(this),!xa(b))for(b=c=this.la.a.parse(b),c=0;cthis.c)throw Error(Ye);this.a=new Ue;this.b=new Wd;this.g=null;this.aa()}t(Xe,u);var Ye=\"[goog.structs.Pool] Min can not be greater than max\";g=Xe.prototype;g.da=function(){var a=r();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.a.length){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}bf.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)ua(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.ma=function(a){Y.H.ma.call(this,a);this.ra()};g.aa=function(){Y.H.aa.call(this);this.ra()};g.w=function(){Y.H.w.call(this);k.clearTimeout(void 0);ua(this.f.a);this.f=null};function Z(a,b,c,d){this.l=a;this.j=!!d;Y.call(this,b,c)}t(Z,Y);Z.prototype.pa=function(){var a=new T,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.o=!0);return a};Z.prototype.sa=function(a){return!a.i&&!a.a};Pe.prototype.createWebChannel=Pe.prototype.a;X.prototype.send=X.prototype.ab;X.prototype.open=X.prototype.$a;X.prototype.close=X.prototype.close;Ec.NO_ERROR=0;Ec.TIMEOUT=8;Ec.HTTP_ERROR=6;Fc.COMPLETE=\"complete\";Gc.EventType=Hc;Hc.OPEN=\"a\";Hc.CLOSE=\"b\";Hc.ERROR=\"c\";Hc.MESSAGE=\"d\";A.prototype.listen=A.prototype.Ha;Z.prototype.getObject=Z.prototype.da;Z.prototype.releaseObject=Z.prototype.jb;T.prototype.listenOnce=T.prototype.Ia;T.prototype.getLastError=T.prototype.bb;T.prototype.getLastErrorCode=T.prototype.Fa;\nT.prototype.getStatus=T.prototype.W;T.prototype.getStatusText=T.prototype.Ga;T.prototype.getResponseJson=T.prototype.Za;T.prototype.getResponseText=T.prototype.V;T.prototype.getResponseText=T.prototype.V;T.prototype.send=T.prototype.fa;module.exports={createWebChannelTransport:Te,ErrorCode:Ec,EventType:Fc,WebChannel:Gc,XhrIoPool:Z};}).call(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11)))\n\n/***/ }),\n\n/***/ 22:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// CONCATENATED MODULE: ../logger/dist/esm/src/logger.js\n/**\n * Copyright 2017 Google Inc.\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 container for all of the Logger instances\n */\nvar instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nvar LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n/**\n * The default log level\n */\nvar defaultLogLevel = LogLevel.INFO;\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nvar defaultLogHandler = function (instance, logType) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (logType < instance.logLevel)\n return;\n var now = new Date().toISOString();\n switch (logType) {\n /**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\n case LogLevel.DEBUG:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.VERBOSE:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.INFO:\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.WARN:\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.ERROR:\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n default:\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\n }\n};\nvar Logger = /** @class */ (function () {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n function Logger(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The log handler for the Logger instance.\n */\n this._logHandler = defaultLogHandler;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n Object.defineProperty(Logger.prototype, \"logLevel\", {\n get: function () {\n return this._logLevel;\n },\n set: function (val) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Logger.prototype, \"logHandler\", {\n get: function () {\n return this._logHandler;\n },\n set: function (val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The functions below are all based on the `console` interface\n */\n Logger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\n };\n Logger.prototype.log = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\n };\n Logger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\n };\n Logger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\n };\n Logger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\n };\n return Logger;\n}());\n\n\n//# sourceMappingURL=logger.js.map\n\n// CONCATENATED MODULE: ../logger/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"setLogLevel\"] = setLogLevel;\n/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, \"Logger\", function() { return Logger; });\n/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, \"LogLevel\", function() { return LogLevel; });\n/**\n * Copyright 2017 Google Inc.\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\nfunction setLogLevel(level) {\n instances.forEach(function (inst) {\n inst.logLevel = level;\n });\n}\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[115]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-firestore.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-firestore.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/firestore');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./firestore/index.js\n// module id = 115\n// module chunks = 1","/**\n * Copyright 2017 Google Inc.\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/* tslint:disable:no-console */\nimport { SDK_VERSION } from '../core/version';\nimport { PlatformSupport } from '../platform/platform';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nvar logClient = new Logger('@firebase/firestore');\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel() {\n if (logClient.logLevel === FirebaseLogLevel.DEBUG) {\n return LogLevel.DEBUG;\n }\n else if (logClient.logLevel === FirebaseLogLevel.SILENT) {\n return LogLevel.SILENT;\n }\n else {\n return LogLevel.ERROR;\n }\n}\nexport function setLogLevel(newLevel) {\n /**\n * Map the new log level to the associated Firebase Log Level\n */\n switch (newLevel) {\n case LogLevel.DEBUG:\n logClient.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case LogLevel.ERROR:\n logClient.logLevel = FirebaseLogLevel.ERROR;\n break;\n case LogLevel.SILENT:\n logClient.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n logClient.error(\"Firestore (\" + SDK_VERSION + \"): Invalid value passed to `setLogLevel`\");\n }\n}\nexport function debug(tag, msg) {\n var obj = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n if (logClient.logLevel <= FirebaseLogLevel.DEBUG) {\n var args = obj.map(argToString);\n logClient.debug.apply(logClient, [\"Firestore (\" + SDK_VERSION + \") [\" + tag + \"]: \" + msg].concat(args));\n }\n}\nexport function error(msg) {\n var obj = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n if (logClient.logLevel <= FirebaseLogLevel.ERROR) {\n var args = obj.map(argToString);\n logClient.error.apply(logClient, [\"Firestore (\" + SDK_VERSION + \"): \" + msg].concat(args));\n }\n}\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n }\n else {\n var platform = PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n }\n catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n\n//# sourceMappingURL=log.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/log.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SDK_VERSION } from '../core/version';\nimport { error } from './log';\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n error(message);\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 new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nexport function assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n\n//# sourceMappingURL=assert.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/assert.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nvar PlatformSupport = /** @class */ (function () {\n function PlatformSupport() {\n }\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n };\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n };\n return PlatformSupport;\n}());\nexport { PlatformSupport };\n/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nexport function emptyByteString() {\n return PlatformSupport.getPlatform().emptyByteString;\n}\n\n//# sourceMappingURL=platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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// We are doing some heavy reflective stuff, lots of any casting necessary\n/* tslint:disable:no-any */\nimport { Code, FirestoreError } from './error';\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nexport function makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n // Copy any static methods/members\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n return PublicConstructor;\n}\n\n//# sourceMappingURL=api.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/api.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from './assert';\nexport function contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nexport function get(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\nexport function size(obj) {\n var count = 0;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nexport function defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\nexport function forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\nexport function forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\nexport function lookupOrInsert(obj, key, valFn) {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\nexport function isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nexport function shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n//# sourceMappingURL=obj.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as obj from './obj';\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nexport function validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" +\n (maxNumberOfArgs + \" arguments, but was called with \") +\n formatPlural(args.length, 'argument') +\n '.');\n }\n}\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nexport function validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" +\n 'array with at least ' +\n (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nexport function validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nexport function validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nexport function validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', '));\n}\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nexport function validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}\n/** Helper to validate the type of a provided input. */\nfunction validateType(functionName, type, inputName, input) {\n if (typeof input !== type || (type === 'object' && !isPlainObject(input))) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" +\n (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\n * Returns true iff it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n Object.getPrototypeOf(input) === Object.prototype);\n}\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input) {\n if (input === undefined) {\n return 'undefined';\n }\n else if (input === null) {\n return 'null';\n }\n else if (typeof input === 'string') {\n if (input.length > 20) {\n input = input.substring(0, 20) + \"...\";\n }\n return JSON.stringify(input);\n }\n else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n }\n else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n }\n else {\n var customObjectName = tryGetCustomObjectType(input);\n if (customObjectName) {\n return \"a custom \" + customObjectName + \" object\";\n }\n else {\n return 'an object';\n }\n }\n }\n else if (typeof input === 'function') {\n return 'a function';\n }\n else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n/** Hacky method to try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n/** Validates the provided argument is defined. */\nexport function validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" +\n \"argument, but it was undefined.\");\n }\n}\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nexport function validateOptionNames(functionName, options, optionNames) {\n obj.forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" +\n 'Available options: ' +\n optionNames.join(', '));\n }\n });\n}\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nexport function invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" +\n (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n\n//# sourceMappingURL=input_validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/input_validation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from './assert';\n// tslint:disable-next-line:class-as-namespace\nvar AutoId = /** @class */ (function () {\n function AutoId() {\n }\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n return AutoId;\n}());\nexport { AutoId };\nexport function primitiveComparator(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nexport function equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n }\n else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Returns the largest lexicographically smaller string of equal or smaller\n * length. Returns an empty string if there is no such predecessor (if the input\n * is empty).\n *\n * Strings returned from this method can be invalid UTF-16 but this is sufficent\n * in use for indexeddb because that depends on lexicographical ordering but\n * shouldn't be used elsewhere.\n */\nexport function immediatePredecessor(s) {\n // We can decrement the last character in the string and be done\n // unless that character is 0 (0x0000), in which case we have to erase the\n // last character.\n var lastIndex = s.length - 1;\n if (s.length === 0) {\n // Special case the empty string.\n return '';\n }\n else if (s.charAt(lastIndex) === '\\0') {\n return s.substring(0, lastIndex);\n }\n else {\n return (s.substring(0, lastIndex) +\n String.fromCharCode(s.charCodeAt(lastIndex) - 1));\n }\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n\n//# sourceMappingURL=misc.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/misc.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available() {\n if (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nvar Blob = /** @class */ (function () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n var binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n var binaryString = Array.prototype.map\n .call(array, function (char) {\n return String.fromCharCode(char);\n })\n .join('');\n return new Blob(binaryString);\n };\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n return buffer;\n };\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n Blob.prototype.isEqual = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n return Blob;\n}());\nexport { Blob };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\nexport var PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/blob.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { DocumentKey } from './document_key';\nexport var TypeOrder;\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder || (TypeOrder = {}));\n/** Defines the return value for pending server timestamps. */\nexport var ServerTimestampBehavior;\n(function (ServerTimestampBehavior) {\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\n/** Holds properties that define field value deserialization options. */\nvar FieldValueOptions = /** @class */ (function () {\n function FieldValueOptions(serverTimestampBehavior) {\n this.serverTimestampBehavior = serverTimestampBehavior;\n }\n FieldValueOptions.fromSnapshotOptions = function (options) {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(ServerTimestampBehavior.Estimate);\n case 'previous':\n return new FieldValueOptions(ServerTimestampBehavior.Previous);\n case 'none': // Fall-through intended.\n case undefined:\n return FieldValueOptions.defaultOptions;\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n };\n FieldValueOptions.defaultOptions = new FieldValueOptions(ServerTimestampBehavior.Default);\n return FieldValueOptions;\n}());\nexport { FieldValueOptions };\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nvar FieldValue = /** @class */ (function () {\n function FieldValue() {\n }\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n return FieldValue;\n}());\nexport { FieldValue };\nvar NullValue = /** @class */ (function (_super) {\n tslib_1.__extends(NullValue, _super);\n function NullValue() {\n var _this = _super.call(this) || this;\n _this.typeOrder = TypeOrder.NullValue;\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n _this.internalValue = null;\n return _this;\n }\n NullValue.prototype.value = function (options) {\n return null;\n };\n NullValue.prototype.isEqual = function (other) {\n return other instanceof NullValue;\n };\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n };\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(FieldValue));\nexport { NullValue };\nvar BooleanValue = /** @class */ (function (_super) {\n tslib_1.__extends(BooleanValue, _super);\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n BooleanValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BooleanValue.prototype.isEqual = function (other) {\n return (other instanceof BooleanValue &&\n this.internalValue === other.internalValue);\n };\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n return this.defaultCompareTo(other);\n };\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(FieldValue));\nexport { BooleanValue };\n/** Base class for IntegerValue and DoubleValue. */\nvar NumberValue = /** @class */ (function (_super) {\n tslib_1.__extends(NumberValue, _super);\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n NumberValue.prototype.value = function (options) {\n return this.internalValue;\n };\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return NumberValue;\n}(FieldValue));\nexport { NumberValue };\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n }\n else if (left > right) {\n return 1;\n }\n else if (left === right) {\n return 0;\n }\n else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n }\n else {\n return 1;\n }\n }\n}\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n }\n else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\nvar IntegerValue = /** @class */ (function (_super) {\n tslib_1.__extends(IntegerValue, _super);\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n IntegerValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n return IntegerValue;\n}(NumberValue));\nexport { IntegerValue };\nvar DoubleValue = /** @class */ (function (_super) {\n tslib_1.__extends(DoubleValue, _super);\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n _this.internalValue = internalValue;\n return _this;\n }\n DoubleValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n }\n else {\n return false;\n }\n };\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue));\nexport { DoubleValue };\n// TODO(b/37267885): Add truncation support\nvar StringValue = /** @class */ (function (_super) {\n tslib_1.__extends(StringValue, _super);\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n StringValue.prototype.value = function (options) {\n return this.internalValue;\n };\n StringValue.prototype.isEqual = function (other) {\n return (other instanceof StringValue && this.internalValue === other.internalValue);\n };\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return StringValue;\n}(FieldValue));\nexport { StringValue };\nvar TimestampValue = /** @class */ (function (_super) {\n tslib_1.__extends(TimestampValue, _super);\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n TimestampValue.prototype.value = function (options) {\n return this.internalValue.toDate();\n };\n TimestampValue.prototype.isEqual = function (other) {\n return (other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue.compareTo(other.internalValue);\n }\n else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n return TimestampValue;\n}(FieldValue));\nexport { TimestampValue };\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * 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 */\nvar ServerTimestampValue = /** @class */ (function (_super) {\n tslib_1.__extends(ServerTimestampValue, _super);\n function ServerTimestampValue(localWriteTime, previousValue) {\n var _this = _super.call(this) || this;\n _this.localWriteTime = localWriteTime;\n _this.previousValue = previousValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n ServerTimestampValue.prototype.value = function (options) {\n if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\n return this.localWriteTime.toDate();\n }\n else if (options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\n return this.previousValue ? this.previousValue.value(options) : null;\n }\n else {\n return null;\n }\n };\n ServerTimestampValue.prototype.isEqual = function (other) {\n return (other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime));\n };\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime.compareTo(other.localWriteTime);\n }\n else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n return ServerTimestampValue;\n}(FieldValue));\nexport { ServerTimestampValue };\nvar BlobValue = /** @class */ (function (_super) {\n tslib_1.__extends(BlobValue, _super);\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n BlobValue.prototype.value = function (options) {\n return this.internalValue;\n };\n BlobValue.prototype.isEqual = function (other) {\n return (other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return BlobValue;\n}(FieldValue));\nexport { BlobValue };\nvar RefValue = /** @class */ (function (_super) {\n tslib_1.__extends(RefValue, _super);\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n RefValue.prototype.value = function (options) {\n return this.key;\n };\n RefValue.prototype.isEqual = function (other) {\n if (other instanceof RefValue) {\n return (this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId));\n }\n else {\n return false;\n }\n };\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n };\n return RefValue;\n}(FieldValue));\nexport { RefValue };\nvar GeoPointValue = /** @class */ (function (_super) {\n tslib_1.__extends(GeoPointValue, _super);\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n GeoPointValue.prototype.value = function (options) {\n return this.internalValue;\n };\n GeoPointValue.prototype.isEqual = function (other) {\n return (other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue));\n };\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n };\n return GeoPointValue;\n}(FieldValue));\nexport { GeoPointValue };\nvar ObjectValue = /** @class */ (function (_super) {\n tslib_1.__extends(ObjectValue, _super);\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n ObjectValue.prototype.value = function (options) {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value(options);\n });\n return result;\n };\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n ObjectValue.prototype.isEqual = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n return !it1.hasNext() && !it2.hasNext();\n }\n return false;\n };\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n }\n else {\n var child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n }\n else {\n // nested field\n var child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n }\n else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n }\n else {\n field = undefined;\n }\n });\n return field;\n };\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\n return ObjectValue;\n}(FieldValue));\nexport { ObjectValue };\nvar ArrayValue = /** @class */ (function (_super) {\n tslib_1.__extends(ArrayValue, _super);\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n ArrayValue.prototype.value = function (options) {\n return this.internalValue.map(function (v) { return v.value(options); });\n };\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n ArrayValue.prototype.isEqual = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n if (cmp) {\n return cmp;\n }\n }\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n }\n else {\n return this.defaultCompareTo(other);\n }\n };\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n return ArrayValue;\n}(FieldValue));\nexport { ArrayValue };\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/field_value.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\nvar NumberAsAny = Number;\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport var MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nexport var isInteger = NumberAsAny.isInteger ||\n (function (value) {\n return typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value;\n });\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value) {\n return value === null || value === undefined;\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 */\nexport function isSafeInteger(value) {\n return (isInteger(value) &&\n value <= MAX_SAFE_INTEGER &&\n value >= MIN_SAFE_INTEGER);\n}\n/**\n * Safely checks if the number is NaN.\n */\nexport function safeIsNaN(value) {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n }\n else {\n return typeof value === 'number' && isNaN(value);\n }\n}\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DoubleValue, NullValue, RefValue } from '../model/field_value';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\nvar Query = /** @class */ (function () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n Query.atPath = function (path) {\n return new Query(path);\n };\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function () {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\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 if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n }\n else {\n this.memoizedOrderBy = [\n new OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n }\n else {\n assert(inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC);\n }\n }\n }\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null ||\n !(filter instanceof RelationFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\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.\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n };\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return str + ')';\n };\n Query.prototype.isEqual = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n if (this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null) {\n return false;\n }\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n };\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0)\n return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n Query.prototype.matches = function (doc) {\n return (this.matchesAncestor(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc));\n };\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n };\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (filter instanceof RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n };\n Query.prototype.isDocumentQuery = function () {\n return DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n }\n else {\n // shallow ancestor queries by default\n return (this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1);\n }\n };\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n // order by key always matches\n if (!orderBy.field.isKeyField() &&\n doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n return true;\n };\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n };\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n return Query;\n}());\nexport { Query };\nvar RelationOp = /** @class */ (function () {\n function RelationOp(name) {\n this.name = name;\n }\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case '==':\n return RelationOp.EQUAL;\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case '>':\n return RelationOp.GREATER_THAN;\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n RelationOp.prototype.isEqual = function (other) {\n return this.name === other.name;\n };\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n return RelationOp;\n}());\nexport { RelationOp };\nvar RelationFilter = /** @class */ (function () {\n function RelationFilter(field, op, value) {\n this.field = field;\n this.op = op;\n this.value = value;\n }\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\n var refValue = this.value;\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n RelationFilter.prototype.matchesValue = function (value) {\n // Only compare types with matching backend order (such as double and int).\n if (this.value.typeOrder !== value.typeOrder) {\n return false;\n }\n return this.matchesComparison(value.compareTo(this.value));\n };\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case RelationOp.LESS_THAN:\n return comparison < 0;\n case RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case RelationOp.EQUAL:\n return comparison === 0;\n case RelationOp.GREATER_THAN:\n return comparison > 0;\n case RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n RelationFilter.prototype.isInequality = function () {\n return this.op !== RelationOp.EQUAL;\n };\n RelationFilter.prototype.canonicalId = function () {\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 (this.field.canonicalString() + this.op.toString() + this.value.toString());\n };\n RelationFilter.prototype.isEqual = function (other) {\n if (other instanceof RelationFilter) {\n return (this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value));\n }\n else {\n return false;\n }\n };\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n return RelationFilter;\n}());\nexport { RelationFilter };\n/**\n * Filter that matches 'null' values.\n */\nvar NullFilter = /** @class */ (function () {\n function NullFilter(field) {\n this.field = field;\n }\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n NullFilter.prototype.isEqual = function (other) {\n if (other instanceof NullFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NullFilter;\n}());\nexport { NullFilter };\n/**\n * Filter that matches 'NaN' values.\n */\nvar NanFilter = /** @class */ (function () {\n function NanFilter(field) {\n this.field = field;\n }\n NanFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field).value();\n return typeof val === 'number' && isNaN(val);\n };\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n NanFilter.prototype.isEqual = function (other) {\n if (other instanceof NanFilter) {\n return this.field.isEqual(other.field);\n }\n else {\n return false;\n }\n };\n return NanFilter;\n}());\nexport { NanFilter };\n/**\n * Creates a filter based on the provided arguments.\n */\nexport function fieldFilter(field, op, value) {\n if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on null.');\n }\n return new NullFilter(field);\n }\n else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals ' + 'comparisons on NaN.');\n }\n return new NanFilter(field);\n }\n else {\n return new RelationFilter(field, op, value);\n }\n}\n/**\n * The direction of sorting in an order by.\n */\nvar Direction = /** @class */ (function () {\n function Direction(name) {\n this.name = name;\n }\n Direction.prototype.toString = function () {\n return this.name;\n };\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}());\nexport { Direction };\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 */\nvar Bound = /** @class */ (function () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n return canonicalId;\n };\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = DocumentKey.comparator(component.key, doc.key);\n }\n else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n };\n Bound.prototype.isEqual = function (other) {\n if (other === null) {\n return false;\n }\n if (this.before !== other.before ||\n this.position.length !== other.position.length) {\n return false;\n }\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.isEqual(otherPosition);\n }\n return true;\n };\n return Bound;\n}());\nexport { Bound };\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nvar OrderBy = /** @class */ (function () {\n function OrderBy(field, dir) {\n this.field = field;\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy\n ? Document.compareByKey(d1, d2)\n : Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n OrderBy.prototype.isEqual = function (other) {\n return this.dir === other.dir && this.field.isEqual(other.field);\n };\n return OrderBy;\n}());\nexport { OrderBy };\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n\n//# sourceMappingURL=query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/query.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\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.\n */\nvar RpcCode;\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\nexport function isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n // TODO(b/37325376): Give up after second unauthenticated error.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.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 Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\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 */\nexport function mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n if (code === undefined) {\n return undefined;\n }\n return mapCodeFromRpcCode(code);\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 */\nexport function mapCodeFromRpcCode(code) {\n if (code === undefined) {\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 log.error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status) {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200:// OK\n return Code.OK;\n case 400:// Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n case 401:// Unauthorized\n return Code.UNAUTHENTICATED;\n case 403:// Forbidden\n return Code.PERMISSION_DENIED;\n case 404:// Not Found\n return Code.NOT_FOUND;\n case 409:// Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n case 416:// Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n case 429:// Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n case 499:// Client Closed Request\n return Code.CANCELLED;\n case 500:// Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n case 501:// Unimplemented\n return Code.UNIMPLEMENTED;\n case 503:// Service Unavailable\n return Code.UNAVAILABLE;\n case 504:// Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n default:\n if (status >= 200 && status < 300)\n return Code.OK;\n if (status >= 400 && status < 500)\n return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600)\n return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n\n//# sourceMappingURL=rpc_error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/rpc_error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { DocumentKey } from './document_key';\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\nexport function documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet() {\n return EMPTY_DOCUMENT_KEY_SET;\n}\n\n//# sourceMappingURL=collections.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/collections.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\nimport { assert, fail } from '../util/assert';\nimport * as objUtils from '../util/obj';\nimport { CurrentStatusUpdate, RemoteEvent, ResetMapping, UpdateMapping } from './remote_event';\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 */\nvar DocumentWatchChange = /** @class */ (function () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds, \n /** The new document is removed from all of these targets. */\n removedTargetIds, \n /** The key of the document for this change. */\n key, \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 newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n return DocumentWatchChange;\n}());\nexport { DocumentWatchChange };\nvar ExistenceFilterChange = /** @class */ (function () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n return ExistenceFilterChange;\n}());\nexport { ExistenceFilterChange };\nexport var WatchTargetChangeState;\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\nvar WatchTargetChange = /** @class */ (function () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state, \n /** The target IDs that were added/removed/set. */\n targetIds, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken, \n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n if (cause === void 0) { cause = null; }\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n return WatchTargetChange;\n}());\nexport { WatchTargetChange };\n/**\n * A helper class to accumulate watch changes into a RemoteEvent and other\n * target information.\n */\nvar WatchChangeAggregator = /** @class */ (function () {\n function WatchChangeAggregator(snapshotVersion, listenTargets, pendingTargetResponses) {\n this.snapshotVersion = snapshotVersion;\n this.listenTargets = listenTargets;\n /** The existence filter - if any - for the given target IDs. */\n this.existenceFilters = {};\n /** Keeps track of the current target mappings */\n this.targetChanges = {};\n /** Keeps track of document to update */\n this.documentUpdates = maybeDocumentMap();\n /** Whether this aggregator was frozen and can no longer be modified */\n this.frozen = false;\n this.pendingTargetResponses = objUtils.shallowCopy(pendingTargetResponses);\n }\n /** Aggregates a watch change into the current state */\n WatchChangeAggregator.prototype.add = function (watchChange) {\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n if (watchChange instanceof DocumentWatchChange) {\n this.addDocumentChange(watchChange);\n }\n else if (watchChange instanceof WatchTargetChange) {\n this.addTargetChange(watchChange);\n }\n else if (watchChange instanceof ExistenceFilterChange) {\n this.addExistenceFilterChange(watchChange);\n }\n else {\n fail('Unknown watch change: ' + watchChange);\n }\n };\n /** Aggregates all provided watch changes to the current state in order */\n WatchChangeAggregator.prototype.addChanges = function (watchChanges) {\n var _this = this;\n assert(!this.frozen, 'Trying to modify frozen WatchChangeAggregator.');\n watchChanges.forEach(function (change) { return _this.add(change); });\n };\n /**\n * Converts the current state into a remote event with the snapshot version\n * provided via the constructor.\n */\n WatchChangeAggregator.prototype.createRemoteEvent = function () {\n var _this = this;\n var targetChanges = this.targetChanges;\n // Remove all the non-active targets from the remote event.\n objUtils.forEachNumber(this.targetChanges, function (targetId) {\n if (!_this.isActiveTarget(targetId)) {\n delete targetChanges[targetId];\n }\n });\n // Mark this aggregator as frozen so no further modifications are made\n this.frozen = true;\n return new RemoteEvent(this.snapshotVersion, targetChanges, this.documentUpdates);\n };\n WatchChangeAggregator.prototype.ensureTargetChange = function (targetId) {\n var change = this.targetChanges[targetId];\n if (!change) {\n // Create an UpdateMapping by default, since resets are always explicit.\n change = {\n currentStatusUpdate: CurrentStatusUpdate.None,\n snapshotVersion: this.snapshotVersion,\n mapping: new UpdateMapping(),\n resumeToken: emptyByteString()\n };\n this.targetChanges[targetId] = change;\n }\n return change;\n };\n /**\n * We need to wait for watch to ack targets before we process those events,\n * so to know if a target is active, there must be no pending acks we're\n * waiting for and it must be in the current list of targets that the client\n * cares about.\n *\n * This method is visible for testing.\n */\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return (!objUtils.contains(this.pendingTargetResponses, targetId) &&\n objUtils.contains(this.listenTargets, targetId));\n };\n WatchChangeAggregator.prototype.addDocumentChange = function (docChange) {\n var relevant = false;\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.add(docChange.key);\n relevant = true;\n }\n }\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n if (this.isActiveTarget(targetId)) {\n var change = this.ensureTargetChange(targetId);\n change.mapping.delete(docChange.key);\n relevant = true;\n }\n }\n // Only update the document if there is a new document to replace to an\n // active target that is being listened to, this might be just a target\n // update instead.\n if (docChange.newDoc && relevant) {\n this.documentUpdates = this.documentUpdates.insert(docChange.key, docChange.newDoc);\n }\n };\n WatchChangeAggregator.prototype.addTargetChange = function (targetChange) {\n var _this = this;\n targetChange.targetIds.forEach(function (targetId) {\n var change = _this.ensureTargetChange(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n // Creating the change above satisfies the semantics of no-change.\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n if (!objUtils.contains(_this.pendingTargetResponses, targetId)) {\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 change.mapping = new UpdateMapping();\n change.currentStatusUpdate = CurrentStatusUpdate.None;\n delete _this.existenceFilters[targetId];\n }\n applyResumeToken(change, targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can\n // post-filter and remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n _this.recordTargetResponse(targetId);\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n change.currentStatusUpdate = CurrentStatusUpdate.MarkCurrent;\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (_this.isActiveTarget(targetId)) {\n // Overwrite any existing target mapping with a reset\n // mapping. Every subsequent update will modify the reset\n // mapping, not an update mapping.\n change.mapping = new ResetMapping();\n applyResumeToken(change, targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\n * Record that we get a watch target add/remove by decrementing the number of\n * pending target responses that we have.\n */\n WatchChangeAggregator.prototype.recordTargetResponse = function (targetId) {\n var newCount = (this.pendingTargetResponses[targetId] || 0) - 1;\n if (newCount === 0) {\n delete this.pendingTargetResponses[targetId];\n }\n else {\n this.pendingTargetResponses[targetId] = newCount;\n }\n };\n WatchChangeAggregator.prototype.addExistenceFilterChange = function (change) {\n if (this.isActiveTarget(change.targetId)) {\n this.existenceFilters[change.targetId] = change.existenceFilter;\n }\n };\n return WatchChangeAggregator;\n}());\nexport { WatchChangeAggregator };\n/**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. null and empty resumeTokens are discarded.\n */\nfunction applyResumeToken(change, resumeToken) {\n if (resumeToken.length > 0) {\n change.resumeToken = resumeToken;\n }\n}\n\n//# sourceMappingURL=watch_change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/watch_change.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Blob } from '../api/blob';\nimport { GeoPoint } from '../api/geo_point';\nimport { DatabaseId } from '../core/database_info';\nimport { Bound, Direction, NanFilter, NullFilter, OrderBy, Query, RelationFilter, RelationOp } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { QueryPurpose } from '../local/query_data';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport * as fieldValue from '../model/field_value';\nimport { DeleteMutation, FieldMask, FieldTransform, MutationResult, PatchMutation, Precondition, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as obj from '../util/obj';\nimport * as typeUtils from '../util/types';\nimport { ExistenceFilter } from './existence_filter';\nimport { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';\nimport { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nvar DIRECTIONS = (function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\nvar OPERATORS = (function () {\n var ops = {};\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[RelationOp.EQUAL.name] = 'EQUAL';\n return ops;\n})();\nfunction assertPresent(value, description) {\n assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');\n}\nfunction parseInt64(value) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n }\n else if (typeof value === 'string') {\n return Number(value);\n }\n else {\n return fail(\"can't parse \" + value);\n }\n}\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nvar JsonProtoSerializer = /** @class */ (function () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n }\n else {\n return new Uint8Array(0);\n }\n };\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\n * Returns a value for a number (or undefined) 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: } struct.\n */\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\n if (!typeUtils.isNullOrUndefined(val)) {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n return { value: val };\n }\n else {\n return undefined;\n }\n };\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\n var result;\n if (typeof val === 'object') {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n result = val.value;\n }\n else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return typeUtils.isNullOrUndefined(result) ? null : result;\n };\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanos\n // tslint:disable-next-line:no-any\n };\n };\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\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 (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return Timestamp.fromISOString(date);\n }\n else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n };\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n */\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n }\n else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return Blob.fromBase64String(blob);\n }\n else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return Blob.fromUint8Array(blob);\n }\n };\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n };\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId);\n assert((!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database);\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n return this.toResourceName(this.databaseId, path);\n };\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n };\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function () {\n var path = new ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n };\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return (path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases');\n };\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof fieldValue.NullValue) {\n return { nullValue: 'NULL_VALUE' };\n }\n else if (val instanceof fieldValue.BooleanValue) {\n return { booleanValue: val.value() };\n }\n else if (val instanceof fieldValue.IntegerValue) {\n return { integerValue: '' + val.value() };\n }\n else if (val instanceof fieldValue.DoubleValue) {\n var doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' };\n }\n else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' };\n }\n else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: val.value() };\n }\n else if (val instanceof fieldValue.StringValue) {\n return { stringValue: val.value() };\n }\n else if (val instanceof fieldValue.ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n }\n else if (val instanceof fieldValue.ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n }\n else if (val instanceof fieldValue.TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n }\n else if (val instanceof fieldValue.GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n }\n else if (val instanceof fieldValue.BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n }\n else if (val instanceof fieldValue.RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n }\n else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this;\n // tslint:disable-next-line:no-any\n var type = obj['value_type'];\n if (hasTag(obj, type, 'nullValue')) {\n return fieldValue.NullValue.INSTANCE;\n }\n else if (hasTag(obj, type, 'booleanValue')) {\n return fieldValue.BooleanValue.of(obj.booleanValue);\n }\n else if (hasTag(obj, type, 'integerValue')) {\n return new fieldValue.IntegerValue(parseInt64(obj.integerValue));\n }\n else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return fieldValue.DoubleValue.NAN;\n }\n else if (obj.doubleValue === 'Infinity') {\n return fieldValue.DoubleValue.POSITIVE_INFINITY;\n }\n else if (obj.doubleValue === '-Infinity') {\n return fieldValue.DoubleValue.NEGATIVE_INFINITY;\n }\n }\n return new fieldValue.DoubleValue(obj.doubleValue);\n }\n else if (hasTag(obj, type, 'stringValue')) {\n return new fieldValue.StringValue(obj.stringValue);\n }\n else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n }\n else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values = obj.arrayValue.values || [];\n return new fieldValue.ArrayValue(values.map(function (v) { return _this.fromValue(v); }));\n }\n else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new fieldValue.TimestampValue(this.fromTimestamp(obj.timestampValue));\n }\n else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));\n }\n else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new fieldValue.BlobValue(blob);\n }\n else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new fieldValue.RefValue(dbId, key);\n }\n else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n JsonProtoSerializer.prototype.fromDocument = function (document) {\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this;\n // Proto map gets mapped to Object, so cast it.\n var map = object;\n var result = fieldValue.ObjectValue.EMPTY;\n obj.forEach(map, function (key, value) {\n result = result.set(new FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return { values: result };\n };\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new Document(key, version, fields, { hasLocalMutations: false });\n };\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n };\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result'];\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n }\n else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc instanceof NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof WatchTargetChange) {\n var cause = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n var watchChange;\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\n }\n else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new Document(key, version, fields, {\n hasLocalMutations: false\n });\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : SnapshotVersion.forDeletedDoc();\n var doc = new NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n }\n else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n }\n else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n }\n else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n };\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n }\n else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n }\n else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n }\n else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n }\n else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n }\n else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n };\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\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 // tslint:disable-next-line:no-any\n var type = change['response_type'];\n if (!hasTag(change, type, 'targetChange')) {\n return SnapshotVersion.MIN;\n }\n var targetChange = change.targetChange;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n };\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n var result;\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n }\n else if (mutation instanceof DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n }\n else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n }\n else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n }\n else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n var precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : Precondition.NONE;\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n }\n else {\n return new SetMutation(key, value, precondition);\n }\n }\n else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n }\n else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new TransformMutation(key, fieldTransforms);\n }\n else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n }\n else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n }\n else {\n return fail('Unknown precondition');\n }\n };\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n }\n else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n }\n else {\n return Precondition.NONE;\n }\n };\n JsonProtoSerializer.prototype.fromWriteResult = function (proto) {\n var _this = this;\n // NOTE: Deletes don't have an updateTime.\n var version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : null;\n var transformResults = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n return new MutationResult(version, transformResults);\n };\n JsonProtoSerializer.prototype.fromWriteResults = function (protos) {\n var _this = this;\n return (protos || []).map(function (proto) { return _this.fromWriteResult(proto); });\n };\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n assert(fieldTransform.transform instanceof ServerTimestampTransform, 'Unknown transform: ' + fieldTransform.transform);\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n };\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown transform proto: ' + JSON.stringify(proto));\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, ServerTimestampTransform.instance);\n };\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return { documents: [this.toQueryPath(query.path)] };\n };\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return Query.atPath(this.fromQueryPath(name));\n };\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = { structuredQuery: {} };\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);\n }\n else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{ collectionId: path.lastSegment() }];\n }\n var where = this.toFilter(query.filters);\n if (where) {\n result.structuredQuery.where = where;\n }\n var orderBy = this.toOrder(query.orderBy);\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n var limit = this.toInt32Value(query.limit);\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n return result;\n };\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n var filterBy = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n var orderBy = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n var limit = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n var startAt = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n var endAt = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n return new Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n if (value == null) {\n return null;\n }\n else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(query) };\n }\n else {\n result = { query: this.toQueryTarget(query) };\n }\n result.targetId = queryData.targetId;\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n return result;\n };\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n if (filters.length === 0)\n return;\n var protos = filters.map(function (filter) {\n return filter instanceof RelationFilter\n ? _this.toRelationFilter(filter)\n : _this.toUnaryFilter(filter);\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n };\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n if (!filter) {\n return [];\n }\n else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n }\n else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n }\n else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters\n .map(function (f) { return _this.fromFilter(f); })\n .reduce(function (accum, current) { return accum.concat(current); });\n }\n else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n if (orderBys.length === 0)\n return;\n return orderBys.map(function (order) { return _this.toPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n return orderBys.map(function (order) { return _this.fromPropertyOrder(order); });\n };\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) { return _this.toValue(component); })\n };\n };\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) { return _this.fromValue(component); });\n return new Bound(position, before);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n };\n // visible for testing\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n };\n // visible for testing\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return RelationOp.EQUAL;\n case 'GREATER_THAN':\n return RelationOp.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return RelationOp.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return RelationOp.LESS_THAN_OR_EQUAL;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n default:\n return fail('Unknown relation');\n }\n };\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return { fieldPath: path.canonicalString() };\n };\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\n };\n // visible for testing\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n };\n // visible for testing\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n }\n else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n };\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n return {\n fieldPaths: fieldMask.fields.map(function (field) { return field.canonicalString(); })\n };\n };\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) { return FieldPath.fromServerFormat(path); });\n return new FieldMask(fields);\n };\n return JsonProtoSerializer;\n}());\nexport { JsonProtoSerializer };\n/**\n * Checks for a specific oneof tag in a protocol buffer message.\n *\n * This intentionally accommodates two distinct cases:\n *\n * 1) Messages containing a type tag: these are the format produced by GRPC in\n * return values. These may contain default-value mappings for all tags in the\n * oneof but the type tag specifies which one was actually set.\n *\n * 2) Messages that don't contain a type tag: these are the format required by\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\n * choke claiming that the tags aren't fields in the Message.\n *\n * Allowing both formats here makes the serializer able to consume the outputs\n * it produces: for all messages it supports, fromX(toX(value)) == value.\n *\n * Note that case 2 suffers from ambiguity: if multiple tags are present\n * without a type tag then the callers are structured in such a way that the\n * first invocation will win. Since we only parse in this mode when parsing\n * the output of a serialize method this works, but it's not a general\n * solution.\n *\n * Unfortunately there is no general solution here because proto3 makes it\n * impossible to distinguish unset from explicitly set fields: both have the\n * default value for the type. Without the type tag but multiple value tags\n * it's possible to have default values for each tag in the oneof and not be\n * able to know which was actually in effect.\n */\nfunction hasTag(obj, type, tag) {\n return type === tag || (!type && tag in obj);\n}\n\n//# sourceMappingURL=serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateNamedArrayAtLeastNumberOfElements } from '../util/input_validation';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nvar FieldPath = /** @class */ (function () {\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 function FieldPath() {\n var fieldNames = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" +\n 'Field names must not be empty.');\n }\n }\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n FieldPath.documentId = function () {\n return FieldPath._DOCUMENT_ID;\n };\n FieldPath.prototype.isEqual = function (other) {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n };\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n FieldPath._DOCUMENT_ID = new FieldPath(InternalFieldPath.keyField().canonicalString());\n return FieldPath;\n}());\nexport { FieldPath };\n/**\n * Matches any characters in a field path string that are reserved.\n */\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nexport function fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (FieldPath.bind.apply(FieldPath, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}\n\n//# sourceMappingURL=field_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentSet } from '../model/document_set';\nimport { CurrentStatusUpdate, ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentChangeSet, SyncState, ViewSnapshot } from './view_snapshot';\nvar AddedLimboDocument = /** @class */ (function () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n return AddedLimboDocument;\n}());\nexport { AddedLimboDocument };\nvar RemovedLimboDocument = /** @class */ (function () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n return RemovedLimboDocument;\n}());\nexport { RemovedLimboDocument };\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 */\nvar View = /** @class */ (function () {\n function View(query, \n /** Documents included in the remote target */\n syncedDocuments) {\n this.query = query;\n this.syncedDocuments = syncedDocuments;\n this.syncState = null;\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 = false;\n /** Documents in the view but not in the remote target */\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n this.mutatedKeys = documentKeySet();\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\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 * @return a new set of docs, changes, and refill flag.\n */\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n var changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n var oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n var newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false;\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 //\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 var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDoc.hasLocalMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n }\n else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n // Calculate change\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual ||\n oldDoc.hasLocalMutations !== newDoc.hasLocalMutations) {\n // only report a change if document actually changed\n if (docsEqual) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n }\n else {\n changeSet.track({ type: ChangeType.Modified, doc: newDoc });\n }\n if (lastDocInLimit &&\n _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n }\n else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n }\n else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n if (lastDocInLimit) {\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 needsRefill = true;\n }\n }\n });\n if (this.query.hasLimit()) {\n // TODO(klimt): Make DocumentSet size be constant time.\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n }\n }\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n /**\n * Updates the view with the given ViewDocumentChanges and updates limbo docs\n * and sync state from the given (optional) target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n View.prototype.applyChanges = function (docChanges, targetChange) {\n var _this = this;\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return (compareChangeType(c1.type, c2.type) ||\n _this.query.docComparator(c1.doc, c2.doc));\n });\n this.applyTargetChange(targetChange);\n var limboChanges = this.updateLimboDocuments();\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges: limboChanges };\n }\n else {\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, newSyncState === SyncState.Local, !docChanges.mutatedKeys.isEmpty(), syncStateChanged);\n return {\n snapshot: snap,\n limboChanges: limboChanges\n };\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 View.prototype.applyOnlineStateChange = function (onlineState) {\n if (this.current && onlineState === OnlineState.Offline) {\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 = false;\n return this.applyChanges({\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n });\n }\n else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n };\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n View.prototype.shouldBeInLimbo = function (key) {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this.syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\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 */\n View.prototype.applyTargetChange = function (targetChange) {\n if (targetChange) {\n var targetMapping = targetChange.mapping;\n if (targetMapping instanceof ResetMapping) {\n this.syncedDocuments = targetMapping.documents;\n }\n else if (targetMapping instanceof UpdateMapping) {\n this.syncedDocuments = targetMapping.applyToKeySet(this.syncedDocuments);\n }\n switch (targetChange.currentStatusUpdate) {\n case CurrentStatusUpdate.MarkCurrent:\n this.current = true;\n break;\n case CurrentStatusUpdate.MarkNotCurrent:\n this.current = false;\n break;\n case CurrentStatusUpdate.None:\n break;\n default:\n fail('Unknown current status update: ' + targetChange.currentStatusUpdate);\n }\n }\n };\n View.prototype.updateLimboDocuments = function () {\n var _this = this;\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n });\n // Diff the new limbo docs with the old limbo docs.\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n return View;\n}());\nexport { View };\nfunction compareChangeType(c1, c2) {\n var order = function (change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case 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 case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n return order(c1) - order(c2);\n}\n\n//# sourceMappingURL=view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nvar escapeChar = '\\u0001';\nvar encodedSeparatorChar = '\\u0001';\nvar encodedNul = '\\u0010';\nvar encodedEscape = '\\u0011';\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encode(path) {\n var result = '';\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\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 */\nexport function decode(path) {\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 var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return ResourcePath.EMPTY_PATH;\n }\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n for (var start = 0; start < length;) {\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 var end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n var next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n }\n else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n start = end + 2;\n }\n return new ResourcePath(segments);\n}\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nexport function prefixSuccessor(path) {\n var c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n\n//# sourceMappingURL=encoded_resource_path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/encoded_resource_path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { encode } from './encoded_resource_path';\nimport { PersistencePromise } from './persistence_promise';\nimport { SnapshotVersion } from '../core/snapshot_version';\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\n * Cache\n * 2. Added targetCount to targetGlobal row.\n */\nexport var SCHEMA_VERSION = 2;\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 */\nexport function createOrUpgradeDb(db, txn, fromVersion, toVersion) {\n // This function currently supports migrating to schema version 1 (Mutation\n // Queue, Query and Remote Document Cache) and schema version 2 (Query\n // counting).\n assert(fromVersion < toVersion && fromVersion >= 0 && toVersion <= 2, 'Unexpected schema upgrade from v${fromVersion} to v{toVersion}.');\n if (fromVersion < 1 && toVersion >= 1) {\n createOwnerStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createRemoteDocumentCache(db);\n }\n var p = PersistencePromise.resolve();\n if (fromVersion < 2 && toVersion >= 2) {\n p = ensureTargetGlobalExists(txn).next(function (targetGlobal) {\n return saveTargetCount(txn, targetGlobal);\n });\n }\n return p;\n}\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nvar DbTimestamp = /** @class */ (function () {\n function DbTimestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n }\n return DbTimestamp;\n}());\nexport { DbTimestamp };\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can be owned by a single tab at a given time. That tab\n * must validate that it is still the owner before every write operation and\n * should regularly write an updated timestamp to prevent other tabs from\n * \"stealing\" ownership of the db.\n */\nvar DbOwner = /** @class */ (function () {\n function DbOwner(ownerId, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /** Name of the IndexedDb object store. */\n DbOwner.store = 'owner';\n return DbOwner;\n}());\nexport { DbOwner };\nfunction createOwnerStore(db) {\n db.createObjectStore(DbOwner.store);\n}\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nvar DbMutationQueue = /** @class */ (function () {\n function DbMutationQueue(\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId, \n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n */\n lastAcknowledgedBatchId, \n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}());\nexport { DbMutationQueue };\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nvar DbMutationBatch = /** @class */ (function () {\n function DbMutationBatch(\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId, \n /**\n * An identifier for this batch, allocated by the mutation queue in a\n * monotonically increasing manner.\n */\n batchId, \n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs, \n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n DbMutationBatch.keyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}());\nexport { DbMutationBatch };\nfunction createMutationQueue(db) {\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath\n });\n db.createObjectStore(DbDocumentMutation.store);\n}\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nvar DbDocumentMutation = /** @class */ (function () {\n function DbDocumentMutation() {\n }\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 DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\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 */\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n DbDocumentMutation.store = 'documentMutations';\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 */\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}());\nexport { DbDocumentMutation };\nfunction createRemoteDocumentCache(db) {\n db.createObjectStore(DbRemoteDocument.store);\n}\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nvar DbNoDocument = /** @class */ (function () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n return DbNoDocument;\n}());\nexport { DbNoDocument };\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb. It\n * represents either a cached document (if it exists) or a cached \"no-document\"\n * (if it is known to not exist).\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nvar DbRemoteDocument = /** @class */ (function () {\n function DbRemoteDocument(\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument, \n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document) {\n this.noDocument = noDocument;\n this.document = document;\n }\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}());\nexport { DbRemoteDocument };\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nvar DbTarget = /** @class */ (function () {\n function DbTarget(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId, \n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId, \n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken, \n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber, \n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}());\nexport { DbTarget };\n/**\n * An object representing an association between a target and a document.\n * Stored in the targetDocument object store to store the documents tracked by a\n * particular target.\n */\nvar DbTargetDocument = /** @class */ (function () {\n function DbTargetDocument(\n /**\n * The targetId identifying a target.\n */\n targetId, \n /**\n * The path to the document, as encoded in the key.\n */\n path) {\n this.targetId = targetId;\n this.path = path;\n }\n /** Name of the IndexedDb object store. */\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}());\nexport { DbTargetDocument };\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nvar DbTargetGlobal = /** @class */ (function () {\n function DbTargetGlobal(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId, \n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber, \n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion, \n /**\n * The number of targets persisted.\n */\n targetCount) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n this.targetCount = targetCount;\n }\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}());\nexport { DbTargetGlobal };\nfunction createQueryCache(db) {\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\n keyPath: DbTargetDocument.keyPath\n });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, { unique: true });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, { unique: true });\n db.createObjectStore(DbTargetGlobal.store);\n}\n/**\n * Counts the number of targets persisted and adds that value to the target\n * global singleton.\n */\nfunction saveTargetCount(txn, metadata) {\n var globalStore = txn.store(DbTargetGlobal.store);\n var targetStore = txn.store(DbTarget.store);\n return targetStore.count().next(function (count) {\n metadata.targetCount = count;\n return globalStore.put(DbTargetGlobal.key, metadata);\n });\n}\n/**\n * Ensures that the target global singleton row exists by adding it if it's\n * missing.\n *\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\n */\nfunction ensureTargetGlobalExists(txn) {\n var globalStore = txn.store(DbTargetGlobal.store);\n return globalStore.get(DbTargetGlobal.key).next(function (metadata) {\n if (metadata != null) {\n return PersistencePromise.resolve(metadata);\n }\n else {\n metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0, \n /*lastListenSequenceNumber=*/ 0, SnapshotVersion.MIN.toTimestamp(), \n /*targetCount=*/ 0);\n return globalStore.put(DbTargetGlobal.key, metadata).next(function () { return metadata; });\n }\n });\n}\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport var ALL_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbOwner.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n//# sourceMappingURL=indexeddb_schema.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_schema.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { PersistencePromise } from './persistence_promise';\nimport { SCHEMA_VERSION } from './indexeddb_schema';\nvar LOG_TAG = 'SimpleDb';\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 */\nvar SimpleDb = /** @class */ (function () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n SimpleDb.openOrCreate = function (name, version, runUpgrade) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(LOG_TAG, 'Opening database:', name);\n return new PersistencePromise(function (resolve, reject) {\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 var request = window.indexedDB.open(name, version);\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onupgradeneeded = function (event) {\n debug(LOG_TAG, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n var db = event.target.result;\n // We are provided a version upgrade transaction from the request, so\n // we wrap that in a SimpleDbTransaction to allow use of our friendlier\n // API for schema migration operations.\n var txn = new SimpleDbTransaction(request.transaction);\n runUpgrade(db, txn, event.oldVersion, SCHEMA_VERSION).next(function () {\n debug(LOG_TAG, 'Database upgrade to version ' + SCHEMA_VERSION + ' complete');\n });\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n SimpleDb.delete = function (name) {\n debug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\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 var ua = window.navigator.userAgent;\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 if (ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0) {\n return false;\n }\n else {\n return true;\n }\n };\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = SimpleDbTransaction.open(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction)\n .catch(function (error) {\n // Abort the transaction if there was an\n // error.\n transaction.abort();\n return PersistencePromise.reject(error);\n })\n .toPromise();\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 return transaction.completionPromise.then(function () { return transactionFnResult; });\n };\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n return SimpleDb;\n}());\nexport { SimpleDb };\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 */\nvar IterationController = /** @class */ (function () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function () {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function () {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function (value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * This function can be called to stop iteration at any point.\n */\n IterationController.prototype.done = function () {\n this.shouldStop = true;\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 */\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n return IterationController;\n}());\nexport { IterationController };\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nvar SimpleDbTransaction = /** @class */ (function () {\n function SimpleDbTransaction(transaction) {\n var _this = this;\n this.transaction = transaction;\n this.aborted = false;\n this.completionPromise = new Promise(function (resolve, reject) {\n // We consider aborting to be \"normal\" and just resolve the promise.\n // May need to revisit if/when we actually need to abort transactions.\n _this.transaction.onabort = _this.transaction.oncomplete = function (event) {\n resolve();\n };\n _this.transaction.onerror = function (event) {\n reject(event.target.error);\n };\n });\n }\n SimpleDbTransaction.open = function (db, mode, objectStoreNames) {\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\n };\n SimpleDbTransaction.prototype.abort = function () {\n if (!this.aborted) {\n debug(LOG_TAG, 'Aborting transaction.');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\n * Returns a SimpleDbStore 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 */\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n };\n return SimpleDbTransaction;\n}());\nexport { SimpleDbTransaction };\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 */\nvar SimpleDbStore = /** @class */ (function () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n if (value !== undefined) {\n debug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n }\n else {\n debug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n return wrapRequest(request);\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 * @return The object with the specified key or null if no object exists.\n */\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n var request = this.store.get(key);\n // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(LOG_TAG, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n SimpleDbStore.prototype.delete = function (key) {\n debug(LOG_TAG, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\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 */\n SimpleDbStore.prototype.count = function () {\n debug(LOG_TAG, 'COUNT', this.store.name);\n var request = this.store.count();\n return wrapRequest(request);\n };\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(LOG_TAG, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (key, value, control) {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n };\n SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (!cursor) {\n resolve();\n return;\n }\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n if (userResult instanceof PersistencePromise) {\n results.push(userResult);\n }\n if (controller.isDone) {\n resolve();\n }\n else if (controller.skipToKey === null) {\n cursor.continue();\n }\n else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(function () {\n return PersistencePromise.waitFor(results);\n });\n };\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n }\n else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n return { index: indexName, range: range };\n };\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n var index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n }\n else {\n return index.openCursor(options.range, direction);\n }\n }\n else {\n return this.store.openCursor(options.range, direction);\n }\n };\n return SimpleDbStore;\n}());\nexport { SimpleDbStore };\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request) {\n return new PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n\n//# sourceMappingURL=simple_db.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/simple_db.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { immediatePredecessor, primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbDocumentMutation, DbMutationBatch, DbMutationQueue } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n/** A mutation queue for a specific user, backed by IndexedDB. */\nvar IndexedDbMutationQueue = /** @class */ (function () {\n function IndexedDbMutationQueue(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n userId, serializer) {\n this.userId = userId;\n this.serializer = serializer;\n this.garbageCollector = null;\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 */\n IndexedDbMutationQueue.forUser = function (user, serializer) {\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 assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isAuthenticated() ? user.uid : '';\n return new IndexedDbMutationQueue(userId, serializer);\n };\n IndexedDbMutationQueue.prototype.start = function (transaction) {\n var _this = this;\n return IndexedDbMutationQueue.loadNextBatchIdFromDb(transaction)\n .next(function (nextBatchId) {\n _this.nextBatchId = nextBatchId;\n return mutationQueuesStore(transaction).get(_this.userId);\n })\n .next(function (metadata) {\n if (!metadata) {\n metadata = new DbMutationQueue(_this.userId, BATCHID_UNKNOWN, \n /*lastStreamToken=*/ '');\n }\n _this.metadata = metadata;\n // On restart, nextBatchId may end up lower than\n // lastAcknowledgedBatchId since it's computed from the queue\n // contents, and there may be no mutations in the queue. In this\n // case, we need to reset lastAcknowledgedBatchId (which is safe\n // since the queue must be empty).\n if (_this.metadata.lastAcknowledgedBatchId >= _this.nextBatchId) {\n return _this.checkEmpty(transaction).next(function (empty) {\n assert(empty, 'Reset nextBatchID is only possible when the queue is empty');\n _this.metadata.lastAcknowledgedBatchId = BATCHID_UNKNOWN;\n return mutationQueuesStore(transaction).put(_this.metadata);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns one larger than the largest batch ID that has been stored. If there\n * are no mutations returns 0. Note that batch IDs are global.\n */\n IndexedDbMutationQueue.loadNextBatchIdFromDb = function (txn) {\n var maxBatchId = BATCHID_UNKNOWN;\n return mutationsStore(txn)\n .iterate({ reverse: true }, function (key, batch, control) {\n var userId = key[0], batchId = key[1];\n if (batchId > maxBatchId) {\n maxBatchId = batch.batchId;\n }\n if (userId === '') {\n // We can't compute a predecessor for the empty string, since it\n // is lexographically first. That also means that no other\n // userIds can come before this one, so we can just exit early.\n control.done();\n }\n else {\n var nextUser = immediatePredecessor(userId);\n control.skip([nextUser]);\n }\n })\n .next(function () { return maxBatchId + 1; });\n };\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, value, control) {\n empty = false;\n control.done();\n })\n .next(function () { return empty; });\n };\n IndexedDbMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n IndexedDbMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastAcknowledgedBatchId);\n };\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n this.metadata.lastAcknowledgedBatchId = batchId;\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.metadata.lastStreamToken);\n };\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.metadata.lastStreamToken = validateStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(this.metadata);\n };\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n var dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n return mutationsStore(transaction)\n .put(dbBatch)\n .next(function () {\n var promises = [];\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n documentMutationsStore(transaction).put(indexKey, DbDocumentMutation.PLACEHOLDER);\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n return batch;\n });\n };\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n return mutationsStore(transaction)\n .get(this.keyForBatchId(batchId))\n .next(function (dbBatch) {\n return dbBatch ? _this.serializer.fromDbMutationBatch(dbBatch) : null;\n });\n };\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n // All batches with batchId <= this.metadata.lastAcknowledgedBatchId have\n // been acknowledged so the first unacknowledged batch after batchID will\n // have a batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, this.metadata.lastAcknowledgedBatchId) + 1;\n var range = IDBKeyRange.lowerBound(this.keyForBatchId(nextBatchId));\n var foundBatch = null;\n return mutationsStore(transaction)\n .iterate({ range: range }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId >= nextBatchId, 'Should have found mutation after ' + nextBatchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n })\n .next(function () { return foundBatch; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(Number.POSITIVE_INFINITY));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var _this = this;\n var range = IDBKeyRange.bound(this.keyForBatchId(BATCHID_UNKNOWN), this.keyForBatchId(batchId));\n return mutationsStore(transaction)\n .loadAll(range)\n .next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) { return _this.serializer.fromDbMutationBatch(dbBatch); });\n });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\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 var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n var mutationKey = _this.keyForBatchId(batchID);\n // Look up the mutation batch in the store.\n // PORTING NOTE: because iteration is callback driven in the web,\n // we just look up the key instead of keeping an open iterator\n // like iOS.\n return mutationsStore(transaction)\n .get(mutationKey)\n .next(function (dbBatch) {\n if (dbBatch === null) {\n fail('Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(dbBatch));\n });\n })\n .next(function () { return results; });\n };\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1;\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\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 var uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, function (indexKey, _, control) {\n var userID = indexKey[0], encodedPath = indexKey[1], batchID = indexKey[2];\n var path = EncodedResourcePath.decode(encodedPath);\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\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 if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(function () {\n var results = [];\n var promises = [];\n // TODO(rockwood): Implement this using iterate.\n uniqueBatchIDs.forEach(function (batchID) {\n var mutationKey = _this.keyForBatchId(batchID);\n promises.push(mutationsStore(transaction)\n .get(mutationKey)\n .next(function (mutation) {\n if (mutation === null) {\n fail('Dangling document-mutation reference found, ' +\n 'which points to ' +\n mutationKey);\n }\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n });\n };\n IndexedDbMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var txn = mutationsStore(transaction);\n var indexTxn = documentMutationsStore(transaction);\n var promises = [];\n var _loop_1 = function (batch) {\n var range = IDBKeyRange.only(this_1.keyForBatchId(batch.batchId));\n var numDeleted = 0;\n var removePromise = txn.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(this_1.userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n if (this_1.garbageCollector !== null) {\n this_1.garbageCollector.addPotentialGarbageKey(mutation.key);\n }\n }\n };\n var this_1 = this;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n _loop_1(batch);\n }\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, function (key, _, control) {\n var userID = key[0];\n if (userID !== _this.userId) {\n control.done();\n return;\n }\n else {\n var path = EncodedResourcePath.decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. Dangling keys: ' +\n danglingMutationReferences.map(function (p) { return p.canonicalString(); }));\n });\n });\n };\n IndexedDbMutationQueue.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n var _this = this;\n var indexKey = DbDocumentMutation.prefixForPath(this.userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, function (key, value, control) {\n var userID = key[0], keyPath = key[1], /*batchID*/ _ = key[2];\n if (userID === _this.userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(function () { return containsKey; });\n };\n /**\n * Creates a [userId, batchId] key for use with the DbMutationQueue object\n * store.\n */\n IndexedDbMutationQueue.prototype.keyForBatchId = function (batchId) {\n return [this.userId, batchId];\n };\n return IndexedDbMutationQueue;\n}());\nexport { IndexedDbMutationQueue };\nfunction validateStreamToken(token) {\n assert(typeof token === 'string', 'Persisting non-string stream token not supported.');\n return token;\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(txn) {\n return getStore(txn, DbMutationBatch.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(txn) {\n return getStore(txn, DbDocumentMutation.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(txn) {\n return getStore(txn, DbMutationQueue.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbQueryCache = /** @class */ (function () {\n function IndexedDbQueryCache(serializer) {\n this.serializer = serializer;\n /**\n * The last received snapshot version. We store this seperately from the\n * metadata to avoid the extra conversion to/from DbTimestamp.\n */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /**\n * A cached copy of the metadata for the query cache.\n */\n this.metadata = null;\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n }\n IndexedDbQueryCache.prototype.start = function (transaction) {\n var _this = this;\n return globalTargetStore(transaction)\n .get(DbTargetGlobal.key)\n .next(function (metadata) {\n assert(metadata !== null, 'Missing metadata row that should be added by schema migration.');\n _this.metadata = metadata;\n var lastSavedVersion = metadata.lastRemoteSnapshotVersion;\n _this.lastRemoteSnapshotVersion = SnapshotVersion.fromTimestamp(new Timestamp(lastSavedVersion.seconds, lastSavedVersion.nanos));\n return PersistencePromise.resolve();\n });\n };\n IndexedDbQueryCache.prototype.getHighestTargetId = function () {\n return this.metadata.highestTargetId;\n };\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n IndexedDbQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n this.metadata.lastRemoteSnapshotVersion = snapshotVersion.toTimestamp();\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n return this.saveQueryData(transaction, queryData).next(function () {\n _this.metadata.targetCount += 1;\n _this.updateMetadataFromQueryData(queryData);\n return _this.saveMetadata(transaction);\n });\n };\n IndexedDbQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n var _this = this;\n return this.saveQueryData(transaction, queryData).next(function () {\n if (_this.updateMetadataFromQueryData(queryData)) {\n return _this.saveMetadata(transaction);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n var _this = this;\n assert(this.metadata.targetCount > 0, 'Removing from an empty query cache');\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId)\n .next(function () { return targetsStore(transaction).delete(queryData.targetId); })\n .next(function () {\n _this.metadata.targetCount -= 1;\n return _this.saveMetadata(transaction);\n });\n };\n IndexedDbQueryCache.prototype.saveMetadata = function (transaction) {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, this.metadata);\n };\n IndexedDbQueryCache.prototype.saveQueryData = function (transaction, queryData) {\n return targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n };\n /**\n * Updates the in-memory version of the metadata to account for values in the\n * given QueryData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n IndexedDbQueryCache.prototype.updateMetadataFromQueryData = function (queryData) {\n var needsUpdate = false;\n if (queryData.targetId > this.metadata.highestTargetId) {\n this.metadata.highestTargetId = queryData.targetId;\n needsUpdate = true;\n }\n // TODO(GC): add sequence number check\n return needsUpdate;\n };\n Object.defineProperty(IndexedDbQueryCache.prototype, \"count\", {\n get: function () {\n return this.metadata.targetCount;\n },\n enumerable: true,\n configurable: true\n });\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this;\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 efficent.\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction)\n .iterate({ range: range, index: DbTarget.queryTargetsIndexName }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the query is\n // actually equal to the requested query.\n if (query.isEqual(found.query)) {\n result = found;\n control.done();\n }\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // Indexeddb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this;\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = EncodedResourcePath.encode(key.path);\n promises.push(store.delete([targetId, path]));\n if (_this.garbageCollector !== null) {\n _this.garbageCollector.addPotentialGarbageKey(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n };\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n return this.notifyGCForRemovedKeys(txn, range).next(function () {\n return store.delete(range);\n });\n };\n IndexedDbQueryCache.prototype.notifyGCForRemovedKeys = function (txn, range) {\n var _this = this;\n var store = documentTargetStore(txn);\n if (this.garbageCollector !== null && this.garbageCollector.isEager) {\n // In order to generate garbage events properly, we need to read these\n // keys before deleting.\n return store.iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n // Paranoid assertion in case the the collector is set to null\n // during the iteration.\n assert(_this.garbageCollector !== null, 'GarbageCollector for query cache set to null during key removal.');\n _this.garbageCollector.addPotentialGarbageKey(docKey);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n };\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var range = IDBKeyRange.bound([targetId], [targetId + 1], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store\n .iterate({ range: range, keysOnly: true }, function (key, _, control) {\n var path = EncodedResourcePath.decode(key[1]);\n var docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(function () { return result; });\n };\n IndexedDbQueryCache.prototype.setGarbageCollector = function (gc) {\n this.garbageCollector = gc;\n };\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n assert(txn !== null, 'Persistence Transaction cannot be null for query cache containsKey');\n var path = EncodedResourcePath.encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)], \n /*lowerOpen=*/ false, \n /*upperOpen=*/ true);\n var count = 0;\n return documentTargetStore(txn)\n .iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (key, _, control) {\n count++;\n control.done();\n })\n .next(function () { return count > 0; });\n };\n return IndexedDbQueryCache;\n}());\nexport { IndexedDbQueryCache };\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(txn) {\n return getStore(txn, DbTarget.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(txn) {\n return getStore(txn, DbTargetGlobal.store);\n}\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nfunction documentTargetStore(txn) {\n return getStore(txn, DbTargetDocument.store);\n}\n/**\n * Helper to get a typed SimpleDbStore from a transaction.\n */\nfunction getStore(txn, store) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\n\n//# sourceMappingURL=indexeddb_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { fail } from '../util/assert';\nimport { DbRemoteDocument } from './indexeddb_schema';\nimport { SimpleDbTransaction } from './simple_db';\nvar IndexedDbRemoteDocumentCache = /** @class */ (function () {\n function IndexedDbRemoteDocumentCache(serializer) {\n this.serializer = serializer;\n }\n IndexedDbRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n return remoteDocumentsStore(transaction).put(dbKey(maybeDocument.key), this.serializer.toDbRemoteDocument(maybeDocument));\n };\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n return remoteDocumentsStore(transaction).delete(dbKey(documentKey));\n };\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(function (dbRemoteDoc) {\n return dbRemoteDoc\n ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc)\n : null;\n });\n };\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n var results = documentMap();\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 var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction)\n .iterate({ range: range }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n }\n else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(function () { return results; });\n };\n return IndexedDbRemoteDocumentCache;\n}());\nexport { IndexedDbRemoteDocumentCache };\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(txn) {\n if (txn instanceof SimpleDbTransaction) {\n return txn.store(DbRemoteDocument.store);\n }\n else {\n return fail('Invalid transaction object provided!');\n }\n}\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n\n//# sourceMappingURL=indexeddb_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../core/timestamp';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { assert, fail } from '../util/assert';\nimport { DbMutationBatch, DbNoDocument, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema';\nimport { QueryData, QueryPurpose } from './query_data';\n/** Serializer for values stored in the LocalStore. */\nvar LocalSerializer = /** @class */ (function () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document);\n }\n else if (remoteDoc.noDocument) {\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var readTime = remoteDoc.noDocument.readTime;\n var timestamp = new Timestamp(readTime.seconds, readTime.nanos);\n return new NoDocument(key, SnapshotVersion.fromTimestamp(timestamp));\n }\n else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n return new DbRemoteDocument(null, doc);\n }\n else {\n var path = maybeDoc.key.path.toArray();\n var timestamp = maybeDoc.version.toTimestamp();\n var readTime = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n return new DbRemoteDocument(new DbNoDocument(path, readTime), null);\n }\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs);\n return new MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /** Decodes a DbTarget into QueryData */\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var readTime = new Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos);\n var version = SnapshotVersion.fromTimestamp(readTime);\n var query;\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n }\n else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' +\n QueryPurpose.Listen +\n ' may be stored, got ' +\n queryData.purpose);\n var timestamp = queryData.snapshotVersion.toTimestamp();\n var dbTimestamp = new DbTimestamp(timestamp.seconds, timestamp.nanos);\n var queryProto;\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n }\n else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.');\n var resumeToken = queryData.resumeToken;\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto);\n };\n return LocalSerializer;\n}());\nexport { LocalSerializer };\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n\n//# sourceMappingURL=local_serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { User } from '../auth/user';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nvar OAuthToken = /** @class */ (function () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = { Authorization: \"Bearer \" + value };\n }\n return OAuthToken;\n}());\nexport { OAuthToken };\n/** A CredentialsProvider that always yields an empty token. */\nvar EmptyCredentialsProvider = /** @class */ (function () {\n function EmptyCredentialsProvider() {\n /**\n * Stores the User listener registered with setUserChangeListener()\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.userListener = null;\n }\n EmptyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(null);\n };\n EmptyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire with initial user.\n listener(User.UNAUTHENTICATED);\n };\n EmptyCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.userListener !== null, 'removeUserChangeListener() when no listener registered');\n this.userListener = null;\n };\n return EmptyCredentialsProvider;\n}());\nexport { EmptyCredentialsProvider };\nvar FirebaseCredentialsProvider = /** @class */ (function () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n this.app = app;\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n this.tokenListener = null;\n /**\n * Counter used to detect if the user changed while a getToken request was\n * outstanding.\n */\n this.userCounter = 0;\n /** The User listener registered with setUserChangeListener(). */\n this.userListener = null;\n // We listen for token changes but all we really care about is knowing when\n // the uid may have changed.\n this.tokenListener = function () {\n var newUser = _this.getUser();\n if (!_this.currentUser || !newUser.isEqual(_this.currentUser)) {\n _this.currentUser = newUser;\n _this.userCounter++;\n if (_this.userListener) {\n _this.userListener(_this.currentUser);\n }\n }\n };\n this.userCounter = 0;\n // Will fire at least once where we set this.currentUser\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n FirebaseCredentialsProvider.prototype.getToken = function (forceRefresh) {\n var _this = this;\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.');\n // Take note of the current value of the userCounter so that this method can\n // fail (with an ABORTED error) if there is a user change while the request\n // is outstanding.\n var initialUserCounter = this.userCounter;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (tokenData) {\n // Cancel the request since the user changed while the request was\n // outstanding so the response is likely for a previous user (which\n // user, we can't be sure).\n if (_this.userCounter !== initialUserCounter) {\n throw new FirestoreError(Code.ABORTED, 'getToken aborted due to uid change.');\n }\n else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n }\n else {\n return null;\n }\n }\n });\n };\n FirebaseCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n assert(!this.userListener, 'Can only call setUserChangeListener() once.');\n this.userListener = listener;\n // Fire the initial event, but only if we received the initial user\n if (this.currentUser) {\n listener(this.currentUser);\n }\n };\n FirebaseCredentialsProvider.prototype.removeUserChangeListener = function () {\n assert(this.tokenListener != null, 'removeUserChangeListener() called twice');\n assert(this.userListener !== null, 'removeUserChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.userListener = null;\n };\n FirebaseCredentialsProvider.prototype.getUser = function () {\n // TODO(mikelehen): Remove this check once we're shipping with firebase.js.\n if (typeof this.app.INTERNAL.getUid !== 'function') {\n fail('This version of the Firestore SDK requires at least version' +\n ' 3.7.0 of firebase.js.');\n }\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n return FirebaseCredentialsProvider;\n}());\nexport { FirebaseCredentialsProvider };\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 * TODO(b/33147818) this implementation violates the current assumption that\n * tokens are immutable. We need to either revisit this assumption or come\n * up with some way for FPA to use the listen/unlisten interface.\n */\nvar FirstPartyToken = /** @class */ (function () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function () {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\n}());\nexport { FirstPartyToken };\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 */\nvar FirstPartyCredentialsProvider = /** @class */ (function () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi &&\n this.gapi['auth'] &&\n this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n FirstPartyCredentialsProvider.prototype.getToken = function (forceRefresh) {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n };\n // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n FirstPartyCredentialsProvider.prototype.setUserChangeListener = function (listener) {\n // Fire with initial uid.\n listener(User.FIRST_PARTY);\n };\n FirstPartyCredentialsProvider.prototype.removeUserChangeListener = function () { };\n return FirstPartyCredentialsProvider;\n}());\nexport { FirstPartyCredentialsProvider };\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n switch (credentials.type) {\n case 'gapi':\n return new FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n case 'provider':\n return credentials.client;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n\n//# sourceMappingURL=credentials.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/credentials.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport function isPartialObserver(obj) {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n var object = obj;\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Timestamp } from '../core/timestamp';\nimport { ObjectValue } from '../model/field_value';\nimport { ArrayValue, BlobValue, BooleanValue, DoubleValue, GeoPointValue, IntegerValue, NullValue, RefValue, StringValue, TimestampValue } from '../model/field_value';\nimport { FieldMask, FieldTransform, PatchMutation, ServerTimestampTransform, SetMutation, TransformMutation } from '../model/mutation';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport * as typeUtils from '../util/types';\nimport { Blob } from './blob';\nimport { FieldPath as ExternalFieldPath, fromDotSeparatedString } from './field_path';\nimport { DeleteFieldValueImpl, FieldValueImpl, ServerTimestampFieldValueImpl } from './field_value';\nimport { GeoPoint } from './geo_point';\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\nvar ParsedSetData = /** @class */ (function () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n if (this.fieldMask !== null) {\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\n }\n else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedSetData;\n}());\nexport { ParsedSetData };\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nvar ParsedUpdateData = /** @class */ (function () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n ];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n };\n return ParsedUpdateData;\n}());\nexport { ParsedUpdateData };\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nvar UserDataSource;\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n UserDataSource[UserDataSource[\"QueryValue\"] = 3] = \"QueryValue\"; // from a where clause or cursor bound\n})(UserDataSource || (UserDataSource = {}));\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.QueryValue:\n return false;\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\nvar ParseContext = /** @class */ (function () {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * 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 function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement;\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath, \n /*arrayElement=*/ false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName, \n /*path=*/ null, \n /*arrayElement=*/ true, this.fieldTransforms, this.fieldMask);\n };\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty()\n ? ''\n : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" +\n reason +\n fieldDescription);\n };\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n ParseContext.prototype.validatePathSegment = function (segment) {\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with __');\n }\n };\n return ParseContext;\n}());\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nvar DocumentKeyReference = /** @class */ (function () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n return DocumentKeyReference;\n}());\nexport { DocumentKeyReference };\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nvar UserDataConverter = /** @class */ (function () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call. */\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new ParsedSetData(updateData, \n /* fieldMask= */ null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n UserDataConverter.prototype.parseMergeData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask = new FieldMask(context.fieldMask);\n return new ParsedSetData(updateData, fieldMask, context.fieldTransforms);\n };\n /** Parse update data from an update() call. */\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n objUtils.forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = _this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values = [value];\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" +\n 'of arguments that alternate between field names and values.');\n }\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values.push(moreFieldsAndValues[i + 1]);\n }\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values[i], childContext);\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n }\n else {\n var parsedValue = this.parseData(value_1, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n var mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n */\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new ParseContext(UserDataSource.QueryValue, methodName, FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n }\n catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\n * Internal helper for parsing user data.\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 * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n // If context.path is null we are already inside an array and we don't\n // support field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseArray(input, context);\n }\n else if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n }\n else {\n // If context.path is null, we are inside an array and we should have\n // already added the root of the array to the field mask.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n return this.parseScalarValue(input, context);\n }\n };\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, context.childContextForArray(entryIndex));\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new ArrayValue(result);\n };\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n var result = new SortedMap(primitiveComparator);\n objUtils.forEach(obj, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n return new ObjectValue(result);\n };\n /**\n * Helper to parse a scalar value (i.e. not an Object or Array)\n *\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n }\n else if (typeof value === 'number') {\n if (typeUtils.isSafeInteger(value)) {\n return new IntegerValue(value);\n }\n else {\n return new DoubleValue(value);\n }\n }\n else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n }\n else if (typeof value === 'string') {\n return new StringValue(value);\n }\n else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\n }\n else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n }\n else if (value instanceof Blob) {\n return new BlobValue(value);\n }\n else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n }\n else if (value instanceof FieldValueImpl) {\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n return null;\n }\n else if (context.dataSource === UserDataSource.Update) {\n assert(context.path == null || context.path.length > 0, 'FieldValue.delete() at the top level should have already' +\n ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' +\n 'of your update data');\n }\n else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() can only be used with update() and set() with {merge:true}');\n }\n }\n else if (value instanceof ServerTimestampFieldValueImpl) {\n if (!isWrite(context.dataSource)) {\n throw context.createError('FieldValue.serverTimestamp() can only be used with set()' +\n ' and update()');\n }\n if (context.path === null) {\n throw context.createError('FieldValue.serverTimestamp() is not currently' +\n ' supported inside arrays');\n }\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n // Return null so this value is omitted from the parsed result.\n return null;\n }\n else {\n return fail('Unknown FieldValue type: ' + value);\n }\n }\n else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n return UserDataConverter;\n}());\nexport { UserDataConverter };\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 */\nfunction looksLikeJsonObject(input) {\n return (typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl));\n}\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n }\n else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(methodName, path) {\n if (path instanceof ExternalFieldPath) {\n return path._internalPath;\n }\n else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n }\n else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\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 split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n }\n catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n\n//# sourceMappingURL=user_data_converter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/user_data_converter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { FieldPath as ExternalFieldPath } from './field_path';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { FirestoreClient } from '../core/firestore_client';\nimport { Bound, Direction, fieldFilter, OrderBy, Query as InternalQuery, RelationFilter, RelationOp } from '../core/query';\nimport { ChangeType } from '../core/view_snapshot';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ArrayValue, FieldValueOptions, ObjectValue, RefValue } from '../model/field_value';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { assert, fail } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { invalidClassError, validateArgType, validateAtLeastNumberOfArgs, validateBetweenNumberOfArgs, validateDefined, validateExactNumberOfArgs, validateNamedOptionalType, validateNamedOptionalPropertyEquals, validateNamedType, validateOptionalArgType, validateOptionNames, valueDescription } from '../util/input_validation';\nimport * as log from '../util/log';\nimport { LogLevel } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { EmptyCredentialsProvider, FirebaseCredentialsProvider, makeCredentialsProvider } from './credentials';\nimport { isPartialObserver } from './observer';\nimport { DocumentKeyReference, fieldPathFromArgument, UserDataConverter } from './user_data_converter';\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nvar FirestoreSettings = /** @class */ (function () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n }\n else {\n validateNamedType('settings', 'string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n }\n FirestoreSettings.prototype.isEqual = function (other) {\n return (this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials);\n };\n return FirestoreSettings;\n}());\nvar FirestoreConfig = /** @class */ (function () {\n function FirestoreConfig() {\n }\n return FirestoreConfig;\n}());\n/**\n * The root reference to the database.\n */\nvar Firestore = /** @class */ (function () {\n function Firestore(databaseIdOrApp) {\n var _this = this;\n // Public for use in tests.\n // TODO(mikelehen): Use modularized initialization instead.\n this._queue = new AsyncQueue();\n this.INTERNAL = {\n delete: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (this._firestoreClient) {\n return [2 /*return*/, this._firestoreClient.shutdown()];\n }\n return [2 /*return*/];\n });\n }); }\n };\n var config = new FirestoreConfig();\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new FirebaseCredentialsProvider(app);\n }\n else {\n var external_1 = databaseIdOrApp;\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new EmptyCredentialsProvider();\n }\n config.settings = new FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n if (objUtils.contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().');\n }\n var newSettings = new FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.');\n }\n this._config.settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n Firestore.prototype.enableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.enableNetwork();\n };\n Firestore.prototype.disableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.disableNetwork();\n };\n Firestore.prototype.enablePersistence = function () {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.');\n }\n return this.configureClient(/* persistence= */ true);\n };\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n this.configureClient(/* persistence= */ false);\n }\n return this._firestoreClient;\n };\n Firestore.prototype.configureClient = function (persistence) {\n var _this = this;\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n var preConverter = function (value) {\n if (value instanceof DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' +\n (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") +\n (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n }\n else {\n return value;\n }\n };\n this._dataConverter = new UserDataConverter(preConverter);\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\n return this._firestoreClient.start(persistence);\n };\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n if (!objUtils.contains(options, 'projectId')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreId' once alpha testers have upgraded.\n if (objUtils.contains(options, 'firestoreId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreId\" is now specified as \"projectId\" in ' +\n 'firebase.initializeApp.');\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n if (objUtils.contains(options, 'firestoreOptions')) {\n // TODO(b/62673263): We can safely remove the special handling of\n // 'firestoreOptions' once alpha testers have upgraded.\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"firestoreOptions\" values are now specified with ' +\n 'Firestore.settings()');\n }\n var projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n return new DatabaseId(projectId);\n };\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function () {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available');\n }\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n };\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new Transaction(_this, transaction));\n });\n };\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new WriteBatch(this);\n };\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function () {\n switch (log.getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + log.getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'string', 1, level);\n switch (level) {\n case 'debug':\n log.setLogLevel(log.LogLevel.DEBUG);\n break;\n case 'error':\n log.setLogLevel(log.LogLevel.ERROR);\n break;\n case 'silent':\n log.setLogLevel(log.LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n };\n return Firestore;\n}());\nexport { Firestore };\n/**\n * A reference to a transaction.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction\n .lookup([ref._key])\n .then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n var doc = docs[0];\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot(_this._firestore, ref._key, null, false);\n }\n return new DocumentSnapshot(_this._firestore, ref._key, doc, false);\n });\n };\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)\n : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n this._transaction.set(ref._key, parsed);\n return this;\n };\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n this._transaction.update(ref._key, parsed);\n return this;\n };\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n };\n return Transaction;\n}());\nexport { Transaction };\nvar WriteBatch = /** @class */ (function () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge\n ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)\n : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n this.verifyNotCommitted();\n var ref;\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\n return this;\n };\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\n return this;\n };\n WriteBatch.prototype.commit = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return [2 /*return*/, this._firestore.ensureClientConfigured().write(this._mutations)];\n }\n return [2 /*return*/];\n });\n });\n };\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +\n 'has been called.');\n }\n };\n return WriteBatch;\n}());\nexport { WriteBatch };\n/**\n * A reference to a particular document in a collection in the database.\n */\nvar DocumentReference = /** @class */ (function () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return new DocumentReference(new DocumentKey(path), firestore);\n };\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function () {\n return new CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function () {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'string', 1, pathString);\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n var path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n };\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return this.firestore === other.firestore && this._key.isEqual(other._key);\n };\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge\n ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value)\n : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\n };\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n var parsed;\n if (typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n }\n else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\n };\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new DeleteMutation(this._key, Precondition.NONE)\n ]);\n };\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n var internalOptions = {\n includeDocumentMetadataChanges: options.includeMetadataChanges,\n includeQueryMetadataChanges: options.includeMetadataChanges\n };\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n };\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache));\n }\n },\n error: errHandler\n });\n var internalListener = this._firestoreClient.listen(InternalQuery.atPath(this._key.path), asyncObserver, options);\n return function () {\n asyncObserver.mute();\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n DocumentReference.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('DocumentReference.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeQueryMetadataChanges: true,\n includeDocumentMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n if (!snap.exists && snap.metadata.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 reject(new FirestoreError(Code.ABORTED, 'Failed to get document because the client is ' + 'offline.'));\n }\n else {\n resolve(snap);\n }\n },\n error: reject\n });\n });\n };\n return DocumentReference;\n}());\nexport { DocumentReference };\nvar SnapshotMetadata = /** @class */ (function () {\n function SnapshotMetadata(hasPendingWrites, fromCache) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n SnapshotMetadata.prototype.isEqual = function (other) {\n return (this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache);\n };\n return SnapshotMetadata;\n}());\nvar DocumentSnapshot = /** @class */ (function () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n }\n DocumentSnapshot.prototype.data = function (options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n return !this._document\n ? undefined\n : this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options));\n };\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== undefined) {\n return this.convertValue(value, FieldValueOptions.fromSnapshotOptions(options));\n }\n }\n return undefined;\n };\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function () {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function () {\n return new DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function () {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function () {\n return new SnapshotMetadata(this._document !== null && this._document.hasLocalMutations, this._fromCache);\n },\n enumerable: true,\n configurable: true\n });\n DocumentSnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)));\n };\n DocumentSnapshot.prototype.convertObject = function (data, options) {\n var _this = this;\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value, options);\n });\n return result;\n };\n DocumentSnapshot.prototype.convertValue = function (value, options) {\n if (value instanceof ObjectValue) {\n return this.convertObject(value, options);\n }\n else if (value instanceof ArrayValue) {\n return this.convertArray(value, options);\n }\n else if (value instanceof RefValue) {\n var key = value.value(options);\n var database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log.error(\"Document \" + this._key.path + \" contains a document \" +\n \"reference within a different database (\" +\n (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") +\n \"supported. It will be treated as a reference in the current \" +\n (\"database (\" + database.projectId + \"/\" + database.database + \") \") +\n \"instead.\");\n }\n return new DocumentReference(key, this._firestore);\n }\n else {\n return value.value(options);\n }\n };\n DocumentSnapshot.prototype.convertArray = function (data, options) {\n var _this = this;\n return data.internalValue.map(function (value) {\n return _this.convertValue(value, options);\n });\n };\n return DocumentSnapshot;\n}());\nexport { DocumentSnapshot };\nvar QueryDocumentSnapshot = /** @class */ (function (_super) {\n tslib_1.__extends(QueryDocumentSnapshot, _super);\n function QueryDocumentSnapshot(firestore, key, document, fromCache) {\n return _super.call(this, firestore, key, document, fromCache) || this;\n }\n QueryDocumentSnapshot.prototype.data = function (options) {\n var data = _super.prototype.data.call(this, options);\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\n return data;\n };\n return QueryDocumentSnapshot;\n}(DocumentSnapshot));\nexport { QueryDocumentSnapshot };\nvar Query = /** @class */ (function () {\n function Query(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n Query.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n if (fieldPath.isKeyField()) {\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it contains a slash.');\n }\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' +\n 'valid document ID if the first parameter is ' +\n 'FieldPath.documentId(), but it was an empty string.');\n }\n var path = this._query.path.child(new ResourcePath([value]));\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\n }\n else if (value instanceof DocumentReference) {\n var ref = value;\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" +\n \"string or a DocumentReference if the first parameter is \" +\n \"FieldPath.documentId(), but it was: \" +\n (valueDescription(value) + \".\"));\n }\n }\n else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n var filter = fieldFilter(fieldPath, RelationOp.fromString(opStr), fieldValue);\n this.validateNewFilter(filter);\n return new Query(this._query.addFilter(filter), this.firestore);\n };\n Query.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);\n var direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n }\n else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n }\n else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" +\n \"expected 'asc' or 'desc'.\");\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().');\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().');\n }\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(this._query.addOrderBy(orderBy), this.firestore);\n };\n Query.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" +\n 'positive.');\n }\n return new Query(this._query.withLimit(n), this.firestore);\n };\n Query.prototype.startAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.startAfter = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withStartAt(bound), this.firestore);\n };\n Query.prototype.endBefore = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields, \n /*before=*/ true);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.endAt = function (docOrField) {\n var fields = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields, \n /*before=*/ false);\n return new Query(this._query.withEndAt(bound), this.firestore);\n };\n Query.prototype.isEqual = function (other) {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (this.firestore === other.firestore && this._query.isEqual(other._query));\n };\n /** Helper function to create a bound from a document or fields */\n Query.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n var snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" +\n (methodName + \"().\"));\n }\n return this.boundFromDocument(methodName, snap._document, before);\n }\n else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\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.\n */\n Query.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = [];\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 (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n }\n else {\n var value = doc.field(orderBy.field);\n if (value !== undefined) {\n components.push(value);\n }\n else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" +\n (\"document for which the field '\" + field + \"' (used as the \") +\n \"orderBy) does not exist.\");\n }\n }\n }\n return new Bound(components, before);\n };\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n Query.prototype.boundFromFields = function (methodName, values, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" +\n \"The number of arguments must be less than or equal to the \" +\n \"number of Query.orderBy() clauses\");\n }\n var components = [];\n for (var i = 0; i < values.length; i++) {\n var rawValue = values[i];\n var orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" +\n (methodName + \"(), but got a \" + typeof rawValue));\n }\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" +\n (methodName + \"()\"));\n }\n var key = new DocumentKey(this._query.path.child(rawValue));\n components.push(new RefValue(this.firestore._databaseId, key));\n }\n else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n components.push(wrapped);\n }\n }\n return new Bound(components, before);\n };\n Query.prototype.onSnapshot = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n if (typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, [\n 'includeQueryMetadataChanges',\n 'includeDocumentMetadataChanges'\n ]);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeDocumentMetadataChanges', options.includeDocumentMetadataChanges);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeQueryMetadataChanges', options.includeQueryMetadataChanges);\n currArg++;\n }\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n }\n else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n return this.onSnapshotInternal(options, observer);\n };\n Query.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n var errHandler = function (err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n var asyncObserver = new AsyncObserver({\n next: function (result) {\n if (observer.next) {\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n Query.prototype.get = function () {\n var _this = this;\n validateExactNumberOfArgs('Query.get', arguments, 0);\n return new Promise(function (resolve, reject) {\n var unlisten = _this.onSnapshotInternal({\n includeDocumentMetadataChanges: false,\n includeQueryMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function (result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n resolve(result);\n },\n error: reject\n });\n });\n };\n Query.prototype.validateNewFilter = function (filter) {\n if (filter instanceof RelationFilter && filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n (\" inequality filters on '\" + existingField.toString() + \"'\") +\n (\" and '\" + filter.field.toString() + \"'\"));\n }\n var firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n }\n };\n Query.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n Query.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" +\n (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") +\n (\"and so you must also use '\" + inequality.toString() + \"' \") +\n \"as your first Query.orderBy(), but your first Query.orderBy() \" +\n (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n return Query;\n}());\nexport { Query };\nvar QuerySnapshot = /** @class */ (function () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\n }\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function () {\n var result = [];\n this.forEach(function (doc) { return result.push(doc); });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function () {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function () {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function () {\n return new Query(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"docChanges\", {\n get: function () {\n if (!this._cachedChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, this._snapshot);\n }\n return this._cachedChanges;\n },\n enumerable: true,\n configurable: true\n });\n /** Check the equality. The call can be very expensive. */\n QuerySnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n return (this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot));\n };\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache);\n };\n return QuerySnapshot;\n}());\nexport { QuerySnapshot };\nvar CollectionReference = /** @class */ (function (_super) {\n tslib_1.__extends(CollectionReference, _super);\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, InternalQuery.atPath(path), firestore) || this;\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n (path.canonicalString() + \" has \" + path.length));\n }\n return _this;\n }\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function () {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function () {\n var parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n }\n else {\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function () {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n validateArgType('CollectionReference.doc', 'string', 1, pathString);\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n var path = ResourcePath.fromString(pathString);\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () { return docRef; });\n };\n return CollectionReference;\n}(Query));\nexport { CollectionReference };\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n validateOptionNames(methodName, options, ['merge']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n return options;\n}\nfunction validateSnapshotOptions(methodName, options) {\n if (options === undefined) {\n return {};\n }\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\n return options;\n}\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n }\n else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n }\n else {\n return documentRef;\n }\n}\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nexport function changesFromSnapshot(firestore, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\n };\n });\n }\n else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache);\n var oldIndex = -1;\n var newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc: doc, oldIndex: oldIndex, newIndex: newIndex };\n });\n }\n}\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\nexport var PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\nexport var PublicTransaction = makeConstructorPrivate(Transaction, 'Use firebase.firestore().runTransaction() instead.');\nexport var PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\nexport var PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\nexport var PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nexport var PublicQueryDocumentSnapshot = makeConstructorPrivate(QueryDocumentSnapshot);\nexport var PublicQuery = makeConstructorPrivate(Query);\nexport var PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nexport var PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.');\n// tslint:enable:variable-name\n\n//# sourceMappingURL=database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/database.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PublicBlob } from '../api/blob';\nimport { Firestore, PublicCollectionReference, PublicDocumentReference, PublicDocumentSnapshot, PublicFirestore, PublicQuery, PublicQueryDocumentSnapshot, PublicQuerySnapshot, PublicTransaction, PublicWriteBatch } from '../api/database';\nimport { FieldPath } from '../api/field_path';\nimport { PublicFieldValue } from '../api/field_value';\nimport { GeoPoint } from '../api/geo_point';\nimport { shallowCopy } from '../util/obj';\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: GeoPoint,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel\n};\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n */\nexport function configureForFirebase(firebase) {\n firebase.INTERNAL.registerService('firestore', function (app) { return new Firestore(app); }, shallowCopy(firestoreNamespace));\n}\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nexport function configureForStandalone(exportObject) {\n var copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = Firestore;\n exportObject['firestore'] = copiedNamespace;\n}\n\n//# sourceMappingURL=config.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform/config.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport './src/platform_browser/browser_init';\nimport { configureForFirebase } from './src/platform/config';\nexport function registerFirestore(instance) {\n configureForFirebase(instance);\n}\nregisterFirestore(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\n/** The semver (www.semver.org) version of the SDK. */\nexport var SDK_VERSION = firebase.SDK_VERSION;\n\n//# sourceMappingURL=version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\n// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\nexport var Code = {\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 class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nvar FirestoreError = /** @class */ (function (_super) {\n tslib_1.__extends(FirestoreError, _super);\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError';\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 = function () { return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message; };\n return _this;\n }\n return FirestoreError;\n}(Error));\nexport { FirestoreError };\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Code, FirestoreError } from '../util/error';\nimport { validateArgType, validateExactNumberOfArgs } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nvar GeoPoint = /** @class */ (function () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n this._lat = latitude;\n this._long = longitude;\n }\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get: function () {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get: function () {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n GeoPoint.prototype.isEqual = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n GeoPoint.prototype._compareTo = function (other) {\n return (primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long));\n };\n return GeoPoint;\n}());\nexport { GeoPoint };\n\n//# sourceMappingURL=geo_point.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/geo_point.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { primitiveComparator } from '../util/misc';\nvar DatabaseInfo = /** @class */ (function () {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\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 */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n return DatabaseInfo;\n}());\nexport { DatabaseInfo };\n/** The default database name for a project. */\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\nvar DatabaseId = /** @class */ (function () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function () {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n DatabaseId.prototype.isEqual = function (other) {\n return (other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database);\n };\n DatabaseId.prototype.compareTo = function (other) {\n return (primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database));\n };\n return DatabaseId;\n}());\nexport { DatabaseId };\n\n//# sourceMappingURL=database_info.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/database_info.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nexport var DOCUMENT_KEY_NAME = '__name__';\n/**\n * Path represents an ordered sequence of string segments.\n */\nvar Path = /** @class */ (function () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\n * An initialization method that can be called from outside the constructor.\n * We need this so that we can have a non-static construct method that returns\n * the polymorphic `this` type.\n */\n Path.prototype.init = function (segments, offset, length) {\n if (offset === undefined) {\n offset = 0;\n }\n else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n if (length === undefined) {\n length = segments.length - offset;\n }\n else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\n * Constructs a new instance of Path using the same concrete type as `this`.\n * We need this instead of using the normal constructor, because polymorphic\n * `this` doesn't work on static methods.\n */\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n Object.defineProperty(Path.prototype, \"length\", {\n get: function () {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.isEqual = function (other) {\n return Path.comparator(this, other) === 0;\n };\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n }\n else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n }\n else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n return true;\n };\n Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n }\n if (p1.length < p2.length)\n return -1;\n if (p1.length > p2.length)\n return 1;\n return 0;\n };\n return Path;\n}());\nexport { Path };\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nvar ResourcePath = /** @class */ (function (_super) {\n tslib_1.__extends(ResourcePath, _super);\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ResourcePath.prototype.canonicalString = function () {\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 ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n ResourcePath.fromString = function (path) {\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 if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n }\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n var segments = path.split('/').filter(function (segment) { return segment.length > 0; });\n return new ResourcePath(segments);\n };\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(Path));\nexport { ResourcePath };\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\nvar FieldPath = /** @class */ (function (_super) {\n tslib_1.__extends(FieldPath, _super);\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n FieldPath.prototype.canonicalString = function () {\n return this.toArray()\n .map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n };\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\n * Returns true if this field references the key of a document.\n */\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\n * The field designating the key of a document.\n */\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_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 */\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n var addCurrentSegment = function () {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" +\n \"with '.', end with '.', or contain '..'\");\n }\n segments.push(current);\n current = '';\n };\n var inBackticks = false;\n while (i < path.length) {\n var c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n var next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);\n }\n current += next;\n i += 2;\n }\n else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n }\n else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n }\n else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n return new FieldPath(segments);\n };\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(Path));\nexport { FieldPath };\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { ResourcePath } from './path';\nvar DocumentKey = /** @class */ (function () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/'));\n }\n DocumentKey.prototype.isEqual = function (other) {\n return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);\n };\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n DocumentKey.comparator = function (k1, k2) {\n return ResourcePath.comparator(k1.path, k2.path);\n };\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new ResourcePath(segments.slice()));\n };\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(ResourcePath.fromString(path));\n };\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\n return DocumentKey;\n}());\nexport { DocumentKey };\n\n//# sourceMappingURL=document_key.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_key.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\nimport { DocumentKey } from './document_key';\nvar Document = /** @class */ (function () {\n function Document(key, version, data, options) {\n this.key = key;\n this.version = version;\n this.data = data;\n this.hasLocalMutations = options.hasLocalMutations;\n }\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n Document.prototype.value = function () {\n return this.data.value();\n };\n Document.prototype.isEqual = function (other) {\n return (other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.data.isEqual(other.data) &&\n this.hasLocalMutations === other.hasLocalMutations);\n };\n Document.prototype.toString = function () {\n return (\"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" +\n (\"{hasLocalMutations: \" + this.hasLocalMutations + \"})\"));\n };\n Document.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n }\n else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n return Document;\n}());\nexport { Document };\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nvar NoDocument = /** @class */ (function () {\n function NoDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n NoDocument.prototype.isEqual = function (other) {\n return (other &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key));\n };\n NoDocument.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n return NoDocument;\n}());\nexport { NoDocument };\n\n//# sourceMappingURL=document.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert, fail } from './assert';\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nvar SortedMap = /** @class */ (function () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : LLRBNode.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns a copy of the map, with the specified key removed.\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n // Returns the value of the node with the given key, or null.\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\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 SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n };\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function () {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n });\n // Returns the minimum key in the map.\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n };\n // Returns the maximum key in the map.\n SortedMap.prototype.maxKey = function () {\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 SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\n });\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 SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n };\n // Returns an iterator over the SortedMap.\n SortedMap.prototype.getIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n };\n SortedMap.prototype.getIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n };\n SortedMap.prototype.getReverseIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n };\n return SortedMap;\n}()); // end SortedMap\nexport { SortedMap };\n// An iterator over an LLRBNode.\nvar SortedMapIterator = /** @class */ (function () {\n function SortedMapIterator(node, startKey, comparator, isReverse) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n }\n else {\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(node);\n if (this.isReverse) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result = { key: node.key, value: node.value };\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0)\n return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n };\n return SortedMapIterator;\n}()); // end SortedMapIterator\nexport { SortedMapIterator };\n// Represents a node in a Left-leaning Red-Black tree.\nvar LLRBNode = /** @class */ (function () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n LLRBNode.prototype.isEmpty = function () {\n return false;\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 LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\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 LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n // Returns the minimum node in the tree.\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min();\n }\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n };\n // Returns the maximum key in the tree.\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n // Returns new tree, with the key/value added.\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed())\n n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n };\n // Returns new tree, with the specified item removed.\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed())\n n = n.rotateRight();\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n };\n LLRBNode.prototype.isRed = function () {\n return this.color;\n };\n // Returns new tree after performing any needed rotations.\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed())\n n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed())\n n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed())\n n = n.colorFlip();\n return n;\n };\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n };\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n // For testing.\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n }\n else {\n return false;\n }\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 LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n var blackDepth = this.left.check();\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n };\n // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}()); // end LLRBNode\nexport { LLRBNode };\n// Represents an empty node (a leaf node in the Red-Black Tree).\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n this.size = 0;\n }\n // Returns a copy of the current node.\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n // Returns a copy of the tree, with the specified key/value added.\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value);\n };\n // Returns a copy of the tree, with the specified key removed.\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n };\n // For testing.\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n return LLRBEmptyNode;\n}()); // end LLRBEmptyNode\nexport { LLRBEmptyNode };\nLLRBNode.EMPTY = new LLRBEmptyNode();\n\n//# sourceMappingURL=sorted_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { emptyByteString } from '../platform/platform';\n/** An enumeration of the different purposes we have for queries. */\nexport var QueryPurpose;\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\n * The query was used to refill a query after an existence filter mismatch.\n */\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose || (QueryPurpose = {}));\n/**\n * An immutable set of metadata that the local store tracks for each query.\n */\nvar QueryData = /** @class */ (function () {\n function QueryData(\n /** The query being listened to. */\n query, \n /**\n * The target ID to which the query corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n targetId, \n /** The purpose of the query. */\n purpose, \n /** The latest snapshot version seen for this target. */\n snapshotVersion, \n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the query. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n resumeToken) {\n if (snapshotVersion === void 0) { snapshotVersion = SnapshotVersion.MIN; }\n if (resumeToken === void 0) { resumeToken = emptyByteString(); }\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\n * Creates a new query data instance with an updated snapshot version and\n * resume token.\n */\n QueryData.prototype.update = function (updated) {\n return new QueryData(this.query, this.targetId, this.purpose, updated.snapshotVersion, updated.resumeToken);\n };\n QueryData.prototype.isEqual = function (other) {\n return (this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.resumeToken === other.resumeToken &&\n this.query.isEqual(other.query));\n };\n return QueryData;\n}());\nexport { QueryData };\n\n//# sourceMappingURL=query_data.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/query_data.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar isoRegExp = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\nvar Timestamp = /** @class */ (function () {\n function Timestamp(seconds, nanos) {\n this.seconds = seconds;\n this.nanos = nanos;\n assert(nanos >= 0, 'timestamp nanoseconds out of range: ' + nanos);\n assert(nanos < 1e9, 'timestamp nanoseconds out of range' + nanos);\n // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n assert(seconds >= -62135596800, 'timestamp seconds out of range: ' + seconds);\n // This will break in the year 10,000.\n assert(seconds < 253402300800, 'timestamp seconds out of range' + seconds);\n }\n Timestamp.now = function () {\n return Timestamp.fromEpochMilliseconds(Date.now());\n };\n Timestamp.fromDate = function (date) {\n return Timestamp.fromEpochMilliseconds(date.getTime());\n };\n Timestamp.fromEpochMilliseconds = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n Timestamp.fromISOString = function (utc) {\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 var nanos = 0;\n var fraction = isoRegExp.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n // Parse the date to get the seconds.\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n Timestamp.prototype.toDate = function () {\n return new Date(this.toEpochMilliseconds());\n };\n Timestamp.prototype.toEpochMilliseconds = function () {\n return this.seconds * 1000 + this.nanos / 1e6;\n };\n Timestamp.prototype.compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanos, other.nanos);\n }\n return primitiveComparator(this.seconds, other.seconds);\n };\n Timestamp.prototype.isEqual = function (other) {\n return other.seconds === this.seconds && other.nanos === this.nanos;\n };\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanos=' + this.nanos + ')';\n };\n return Timestamp;\n}());\nexport { Timestamp };\n\n//# sourceMappingURL=timestamp.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/timestamp.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { Timestamp } from './timestamp';\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nvar SnapshotVersion = /** @class */ (function () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n }\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n };\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp.compareTo(other.timestamp);\n };\n SnapshotVersion.prototype.isEqual = function (other) {\n return this.timestamp.isEqual(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanos / 1000;\n };\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\n return SnapshotVersion;\n}());\nexport { SnapshotVersion };\n\n//# sourceMappingURL=snapshot_version.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/snapshot_version.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { Document, NoDocument } from './document';\nimport { ObjectValue, ServerTimestampValue } from './field_value';\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 */\nvar FieldMask = /** @class */ (function () {\n function FieldMask(fields) {\n this.fields = fields;\n // TODO(dimond): validation of FieldMask\n }\n FieldMask.prototype.isEqual = function (other) {\n return misc.arrayEquals(this.fields, other.fields);\n };\n return FieldMask;\n}());\nexport { FieldMask };\n/** Transforms a value into a server-generated timestamp. */\nvar ServerTimestampTransform = /** @class */ (function () {\n function ServerTimestampTransform() {\n }\n ServerTimestampTransform.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}());\nexport { ServerTimestampTransform };\n/** A field path and the TransformOperation to perform upon it. */\nvar FieldTransform = /** @class */ (function () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n FieldTransform.prototype.isEqual = function (other) {\n return (this.field.isEqual(other.field) && this.transform.isEqual(other.transform));\n };\n return FieldTransform;\n}());\nexport { FieldTransform };\n/** The result of successfully applying a mutation to the backend. */\nvar MutationResult = /** @class */ (function () {\n function MutationResult(\n /**\n * The version at which the mutation was committed or null for a delete.\n */\n version, \n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n return MutationResult;\n}());\nexport { MutationResult };\nexport var MutationType;\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType || (MutationType = {}));\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 */\nvar Precondition = /** @class */ (function () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function () {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return (maybeDoc instanceof Document &&\n maybeDoc.version.isEqual(this.updateTime));\n }\n else if (this.exists !== undefined) {\n if (this.exists) {\n return maybeDoc instanceof Document;\n }\n else {\n return maybeDoc === null || maybeDoc instanceof NoDocument;\n }\n }\n else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n Precondition.prototype.isEqual = function (other) {\n return (misc.equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists);\n };\n Precondition.NONE = new Precondition();\n return Precondition;\n}());\nexport { Precondition };\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 it version.\n * In the case of Set, Patch, and Transform mutations we preserve the existing\n * version. In the case of Delete mutations, we 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 null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nvar Mutation = /** @class */ (function () {\n function Mutation() {\n }\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n }\n else {\n return SnapshotVersion.MIN;\n }\n };\n return Mutation;\n}());\nexport { Mutation };\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nvar SetMutation = /** @class */ (function (_super) {\n tslib_1.__extends(SetMutation, _super);\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.');\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 var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: false\n });\n };\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n SetMutation.prototype.isEqual = function (other) {\n return (other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition));\n };\n return SetMutation;\n}(Mutation));\nexport { SetMutation };\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 */\nvar PatchMutation = /** @class */ (function (_super) {\n tslib_1.__extends(PatchMutation, _super);\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: false\n });\n };\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n PatchMutation.prototype.isEqual = function (other) {\n return (other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data;\n }\n else {\n data = ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n };\n PatchMutation.prototype.patchObject = function (data) {\n for (var _i = 0, _a = this.fieldMask.fields; _i < _a.length; _i++) {\n var fieldPath = _a[_i];\n var newValue = this.data.field(fieldPath);\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n }\n else {\n data = data.delete(fieldPath);\n }\n }\n return data;\n };\n return PatchMutation;\n}(Mutation));\nexport { PatchMutation };\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nvar TransformMutation = /** @class */ (function (_super) {\n tslib_1.__extends(TransformMutation, _super);\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform;\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n _this.precondition = Precondition.exists(true);\n return _this;\n }\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n var transformResults = mutationResult.transformResults;\n // TODO(mcg): Relax enforcement of this precondition\n //\n // We shouldn't actually enforce the precondition since it already passed on\n // the backend, but we may not have a local version of the document to\n // patch, so we use the precondition to prevent incorrectly putting a\n // partial document into our cache.\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: false\n });\n };\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n TransformMutation.prototype.isEqual = function (other) {\n return (other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n misc.arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition));\n };\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\n return doc;\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 * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\n var transformResults = [];\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n var previousValue = null;\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n transformResults.push(new ServerTimestampValue(localWriteTime, previousValue));\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return transformResults;\n };\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var fieldPath = fieldTransform.field;\n if (transform instanceof ServerTimestampTransform) {\n data = data.set(fieldPath, transformResults[i]);\n }\n else {\n return fail('Encountered unknown transform: ' + transform);\n }\n }\n return data;\n };\n return TransformMutation;\n}(Mutation));\nexport { TransformMutation };\n/** A mutation that deletes the document at the given key. */\nvar DeleteMutation = /** @class */ (function (_super) {\n tslib_1.__extends(DeleteMutation, _super);\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.');\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 return new NoDocument(this.key, SnapshotVersion.MIN);\n };\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\n }\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n };\n DeleteMutation.prototype.isEqual = function (other) {\n return (other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition));\n };\n return DeleteMutation;\n}(Mutation));\nexport { DeleteMutation };\n\n//# sourceMappingURL=mutation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar ExistenceFilter = /** @class */ (function () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n ExistenceFilter.prototype.isEqual = function (other) {\n return other && other.count === this.count;\n };\n return ExistenceFilter;\n}());\nexport { ExistenceFilter };\n\n//# sourceMappingURL=existence_filter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/existence_filter.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SortedMap } from './sorted_map';\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 */\nvar SortedSet = /** @class */ (function () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new SortedMap(this.comparator);\n }\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function () {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0)\n return;\n cb(elem.key);\n }\n };\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n }\n else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result)\n return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem))\n return this;\n return this.copy(this.data.remove(elem));\n };\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n SortedSet.prototype.isEqual = function (other) {\n if (!(other instanceof SortedSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0)\n return false;\n }\n return true;\n };\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) { return result.push(elem); });\n return 'SortedSet(' + result.toString() + ')';\n };\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n return SortedSet;\n}());\nexport { SortedSet };\n\n//# sourceMappingURL=sorted_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/sorted_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet } from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\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 */\nvar RemoteEvent = /** @class */ (function () {\n function RemoteEvent(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n snapshotVersion, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n targetChanges, \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 documentUpdates) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.documentUpdates = documentUpdates;\n }\n RemoteEvent.prototype.addDocumentUpdate = function (doc) {\n this.documentUpdates = this.documentUpdates.insert(doc.key, doc);\n };\n RemoteEvent.prototype.handleExistenceFilterMismatch = function (targetId) {\n /*\n * An existence filter mismatch will reset the query and we need to reset\n * the mapping to contain no documents and an empty resume token.\n *\n * Note:\n * * The reset mapping is empty, specifically forcing the consumer of the\n * change to forget all keys for this targetID;\n * * The resume snapshot for this target must be reset\n * * The target must be unacked because unwatching and rewatching\n * introduces a race for changes.\n */\n this.targetChanges[targetId] = {\n mapping: new ResetMapping(),\n snapshotVersion: SnapshotVersion.MIN,\n currentStatusUpdate: CurrentStatusUpdate.MarkNotCurrent,\n resumeToken: emptyByteString()\n };\n };\n return RemoteEvent;\n}());\nexport { RemoteEvent };\n/**\n * Represents an update to the current status of a target, either explicitly\n * having no new state, or the new value to set. Note \"current\" has special\n * meaning for in the RPC protocol that implies that a target is both up-to-date\n * and consistent with the rest of the watch stream.\n */\nexport var CurrentStatusUpdate;\n(function (CurrentStatusUpdate) {\n /** The current status is not affected and should not be modified. */\n CurrentStatusUpdate[CurrentStatusUpdate[\"None\"] = 0] = \"None\";\n /** The target must be marked as no longer \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkNotCurrent\"] = 1] = \"MarkNotCurrent\";\n /** The target must be marked as \"current\". */\n CurrentStatusUpdate[CurrentStatusUpdate[\"MarkCurrent\"] = 2] = \"MarkCurrent\";\n})(CurrentStatusUpdate || (CurrentStatusUpdate = {}));\nvar EMPTY_KEY_SET = documentKeySet();\nvar ResetMapping = /** @class */ (function () {\n function ResetMapping() {\n this.docs = EMPTY_KEY_SET;\n }\n Object.defineProperty(ResetMapping.prototype, \"documents\", {\n get: function () {\n return this.docs;\n },\n enumerable: true,\n configurable: true\n });\n ResetMapping.prototype.add = function (key) {\n this.docs = this.docs.add(key);\n };\n ResetMapping.prototype.delete = function (key) {\n this.docs = this.docs.delete(key);\n };\n ResetMapping.prototype.isEqual = function (other) {\n return other !== null && this.docs.isEqual(other.docs);\n };\n return ResetMapping;\n}());\nexport { ResetMapping };\nvar UpdateMapping = /** @class */ (function () {\n function UpdateMapping() {\n this.addedDocuments = EMPTY_KEY_SET;\n this.removedDocuments = EMPTY_KEY_SET;\n }\n UpdateMapping.prototype.applyToKeySet = function (keys) {\n var result = keys;\n this.addedDocuments.forEach(function (key) { return (result = result.add(key)); });\n this.removedDocuments.forEach(function (key) { return (result = result.delete(key)); });\n return result;\n };\n UpdateMapping.prototype.add = function (key) {\n this.addedDocuments = this.addedDocuments.add(key);\n this.removedDocuments = this.removedDocuments.delete(key);\n };\n UpdateMapping.prototype.delete = function (key) {\n this.addedDocuments = this.addedDocuments.delete(key);\n this.removedDocuments = this.removedDocuments.add(key);\n };\n UpdateMapping.prototype.isEqual = function (other) {\n return (other !== null &&\n this.addedDocuments.isEqual(other.addedDocuments) &&\n this.removedDocuments.isEqual(other.removedDocuments));\n };\n return UpdateMapping;\n}());\nexport { UpdateMapping };\n\n//# sourceMappingURL=remote_event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_event.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\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 */\nvar StreamBridge = /** @class */ (function () {\n function StreamBridge(args) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\n this.wrappedOnOpen();\n };\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\n this.wrappedOnClose(err);\n };\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\n this.wrappedOnMessage(msg);\n };\n return StreamBridge;\n}());\nexport { StreamBridge };\n\n//# sourceMappingURL=stream_bridge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/stream_bridge.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ErrorCode, EventType, WebChannel, XhrIoPool, createWebChannelTransport } from '@firebase/webchannel-wrapper';\nimport { SDK_VERSION } from '../core/version';\nimport { mapCodeFromHttpStatus, mapCodeFromRpcStatus } from '../remote/rpc_error';\nimport { StreamBridge } from '../remote/stream_bridge';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nvar LOG_TAG = 'Connection';\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\nvar RPC_URL_VERSION = 'v1beta1';\n/** Maps RPC names to the corresponding REST endpoint name. */\nvar RPC_NAME_REST_MAPPING = {\n BatchGetDocuments: 'batchGet',\n Commit: 'commit'\n};\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\nvar WebChannelConnection = /** @class */ (function () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new XhrIoPool();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n };\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\n var _this = this;\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(EventType.COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n var json = xhr.getResponseJson();\n log.debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n case ErrorCode.HTTP_ERROR:\n var status_1 = xhr.getStatus();\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n }\n else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n break;\n default:\n fail('RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.');\n }\n }\n finally {\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n log.debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n var headers = { 'Content-Type': 'text/plain' };\n _this.modifyHeadersForRequest(headers, token);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(rpcName, request, token);\n };\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n var webchannelTransport = createWebChannelTransport();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n // Send our custom headers as a '$httpHeaders=' url param to avoid CORS\n // preflight round-trip. This is formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L40\n httpHeadersOverwriteParam: '$httpHeaders',\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: true,\n supportsCrossDomainXhr: true\n };\n this.modifyHeadersForRequest(request.initMessageHeaders, token);\n var url = urlParts.join('');\n log.debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n // tslint:disable-next-line:no-any Because listen isn't defined on it.\n var channel = webchannelTransport.createWebChannel(url, request);\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 var opened = false;\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 var closed = false;\n var streamBridge = new StreamBridge({\n sendFn: function (msg) {\n if (!closed) {\n if (!opened) {\n log.debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n log.debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n }\n else {\n log.debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function () { return channel.close(); }\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 var unguardedEventListen = function (type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n }\n catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n unguardedEventListen(WebChannel.EventType.OPEN, function () {\n if (!closed) {\n log.debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(WebChannel.EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(WebChannel.EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(WebChannel.EventType.MESSAGE, function (msg) {\n if (!closed) {\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\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 var error = \n // tslint:disable-next-line:no-any msgData.error is not typed.\n msgData.error || (msgData[0] && msgData[0].error);\n if (error) {\n log.debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n var status_2 = error.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status_2 +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n }\n else {\n log.debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\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 streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n };\n // visible for testing\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(urlRpcName);\n return url.join('');\n };\n return WebChannelConnection;\n}());\nexport { WebChannelConnection };\n\n//# sourceMappingURL=webchannel_connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/webchannel_connection.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { WebChannelConnection } from './webchannel_connection';\nvar BrowserPlatform = /** @class */ (function () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n };\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\n };\n BrowserPlatform.prototype.formatJSON = function (value) {\n return JSON.stringify(value);\n };\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n return BrowserPlatform;\n}());\nexport { BrowserPlatform };\n\n//# sourceMappingURL=browser_platform.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_platform.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { PlatformSupport } from '../platform/platform';\nimport { BrowserPlatform } from './browser_platform';\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nPlatformSupport.setPlatform(new BrowserPlatform());\n\n//# sourceMappingURL=browser_init.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/platform_browser/browser_init.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nexport var OnlineState;\n(function (OnlineState) {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n OnlineState[OnlineState[\"Online\"] = 1] = \"Online\";\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n OnlineState[OnlineState[\"Offline\"] = 2] = \"Offline\";\n})(OnlineState || (OnlineState = {}));\n\n//# sourceMappingURL=types.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/types.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nexport var ChangeType;\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType || (ChangeType = {}));\nexport var SyncState;\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState || (SyncState = {}));\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nvar DocumentChangeSet = /** @class */ (function () {\n function DocumentChangeSet() {\n this.changeMap = new SortedMap(DocumentKey.comparator);\n }\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n // Merge the new change with the existing change.\n if (change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n }\n else if (change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n }\n else if (change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n }\n else if (change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n }\n else {\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('unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange));\n }\n };\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n return DocumentChangeSet;\n}());\nexport { DocumentChangeSet };\nvar ViewSnapshot = /** @class */ (function () {\n function ViewSnapshot(query, docs, oldDocs, docChanges, fromCache, hasPendingWrites, syncStateChanged) {\n this.query = query;\n this.docs = docs;\n this.oldDocs = oldDocs;\n this.docChanges = docChanges;\n this.fromCache = fromCache;\n this.hasPendingWrites = hasPendingWrites;\n this.syncStateChanged = syncStateChanged;\n }\n ViewSnapshot.prototype.isEqual = function (other) {\n if (this.fromCache !== other.fromCache ||\n this.hasPendingWrites !== other.hasPendingWrites ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)) {\n return false;\n }\n var changes = this.docChanges;\n var otherChanges = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (var i = 0; i < changes.length; i++) {\n if (changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)) {\n return false;\n }\n }\n return true;\n };\n return ViewSnapshot;\n}());\nexport { ViewSnapshot };\n\n//# sourceMappingURL=view_snapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/view_snapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"LocalStore\"] = 0] = \"LocalStore\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\";\n})(GeneratorIds || (GeneratorIds = {}));\n/**\n * TargetIdGenerator generates monotonically increasing integer IDs. There are\n * separate generators for different scopes. While these generators will operate\n * independently of each other, they are scoped, such that no two generators\n * will ever produce the same ID. This is useful, because sometimes the backend\n * may group IDs from separate parts of the client into the same ID space.\n */\nvar TargetIdGenerator = /** @class */ (function () {\n function TargetIdGenerator(generatorId, initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n this.generatorId = generatorId;\n // Replace the generator part of initAfter with this generator's ID.\n var afterWithoutGenerator = (initAfter >> RESERVED_BITS) << RESERVED_BITS;\n var afterGenerator = initAfter - afterWithoutGenerator;\n if (afterGenerator >= generatorId) {\n // For example, if:\n // this.generatorId = 0b0000\n // after = 0b1011\n // afterGenerator = 0b0001\n // Then:\n // previous = 0b1010\n // next = 0b1100\n this.previousId = afterWithoutGenerator | this.generatorId;\n }\n else {\n // For example, if:\n // this.generatorId = 0b0001\n // after = 0b1010\n // afterGenerator = 0b0000\n // Then:\n // previous = 0b1001\n // next = 0b1011\n this.previousId =\n (afterWithoutGenerator | this.generatorId) - (1 << RESERVED_BITS);\n }\n }\n TargetIdGenerator.prototype.next = function () {\n this.previousId += 1 << RESERVED_BITS;\n return this.previousId;\n };\n TargetIdGenerator.forLocalStore = function (initAfter) {\n if (initAfter === void 0) { initAfter = 0; }\n return new TargetIdGenerator(GeneratorIds.LocalStore, initAfter);\n };\n TargetIdGenerator.forSyncEngine = function () {\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n return TargetIdGenerator;\n}());\nexport { TargetIdGenerator };\n\n//# sourceMappingURL=target_id_generator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/target_id_generator.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SortedMap } from '../util/sorted_map';\nimport { documentMap } from './collections';\nimport { DocumentKey } from './document_key';\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 */\nvar DocumentSet = /** @class */ (function () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = function (d1, d2) {\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n };\n }\n else {\n this.comparator = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n }\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n DocumentSet.prototype.isEmpty = function () {\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 */\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function () {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n if (!doc) {\n return this;\n }\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n DocumentSet.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSet))\n return false;\n if (this.size !== other.size)\n return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc))\n return false;\n }\n return true;\n };\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n }\n else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n return DocumentSet;\n}());\nexport { DocumentSet };\n\n//# sourceMappingURL=document_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/document_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as objUtil from './obj';\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nvar ObjectMap = /** @class */ (function () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i], otherKey = _a[0], value = _a[1];\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n };\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n };\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n }\n else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n };\n ObjectMap.prototype.forEach = function (fn) {\n objUtil.forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i], k = _a[0], v = _a[1];\n fn(k, v);\n }\n });\n };\n ObjectMap.prototype.isEmpty = function () {\n return objUtil.isEmpty(this.inner);\n };\n return ObjectMap;\n}());\nexport { ObjectMap };\n\n//# sourceMappingURL=obj_map.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/obj_map.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { OnlineState } from './types';\nimport { ChangeType, ViewSnapshot } from './view_snapshot';\nimport { DocumentSet } from '../model/document_set';\nimport { assert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nvar QueryListenersInfo = /** @class */ (function () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n return QueryListenersInfo;\n}());\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nvar EventManager = /** @class */ (function () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this.onChange.bind(this), this.onError.bind(this));\n }\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n listener.applyOnlineStateChange(this.onlineState);\n if (queryInfo.viewSnap)\n listener.onViewSnapshot(queryInfo.viewSnap);\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n }\n else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n EventManager.prototype.unlisten = function (listener) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var query, lastListen, queryInfo, i;\n return tslib_1.__generator(this, function (_a) {\n query = listener.query;\n lastListen = false;\n queryInfo = this.queries.get(query);\n if (queryInfo) {\n i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n if (lastListen) {\n this.queries.delete(query);\n return [2 /*return*/, this.syncEngine.unlisten(query)];\n }\n return [2 /*return*/];\n });\n });\n };\n EventManager.prototype.onChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n EventManager.prototype.onError = function (query, error) {\n var queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n }\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n };\n EventManager.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.applyOnlineStateChange(onlineState);\n }\n });\n };\n return EventManager;\n}());\nexport { EventManager };\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 */\nvar QueryListener = /** @class */ (function () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\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.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n if (!this.options.includeDocumentMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.fromCache, snap.hasPendingWrites, snap.syncStateChanged);\n }\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n }\n else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n this.snap = snap;\n };\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n if (this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event');\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n var maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n }\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\n };\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\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 (snap.docChanges.length > 0) {\n return true;\n }\n var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeQueryMetadataChanges === true;\n }\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 return false;\n };\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = new ViewSnapshot(snap.query, snap.docs, DocumentSet.emptySet(snap.docs), QueryListener.getInitialViewChanges(snap), snap.fromCache, snap.hasPendingWrites, true);\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n /** Returns changes as if all documents in the snap were added. */\n QueryListener.getInitialViewChanges = function (snap) {\n var result = [];\n snap.docs.forEach(function (doc) {\n result.push({ type: ChangeType.Added, doc: doc });\n });\n return result;\n };\n return QueryListener;\n}());\nexport { QueryListener };\n\n//# sourceMappingURL=event_manager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/event_manager.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { fail } from '../util/assert';\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 */\nvar PersistencePromise = /** @class */ (function () {\n function PersistencePromise(callback) {\n var _this = this;\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\n this.nextCallback = null;\n // tslint:disable-next-line:no-any Accept any result type for the error handler.\n this.catchCallback = null;\n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = undefined;\n this.error = undefined;\n this.isDone = false;\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n if (_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(value);\n }\n }, function (error) {\n _this.isDone = true;\n _this.error = error;\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result);\n }\n else {\n return this.wrapFailure(catchFn, this.error);\n }\n }\n else {\n return new PersistencePromise(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n }\n else {\n return PersistencePromise.resolve(result);\n }\n }\n catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () { return nextFn(value); });\n }\n else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n // tslint:disable-next-line:no-any\n return PersistencePromise.resolve(value);\n }\n };\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () { return catchFn(error); });\n }\n else {\n return PersistencePromise.reject(error);\n }\n };\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n PersistencePromise.waitFor = function (\n // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\n all) {\n return all.reduce(function (promise, nextPromise, idx) {\n return promise.next(function () {\n return nextPromise;\n });\n }, PersistencePromise.resolve());\n };\n PersistencePromise.map = function (all) {\n var results = [];\n var first = true;\n // initial is ignored, so we can cheat on the type.\n // tslint:disable-next-line:no-any\n var initial = PersistencePromise.resolve(null);\n return all\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (!first) {\n results.push(result);\n }\n first = false;\n return nextPromise;\n });\n }, initial)\n .next(function (result) {\n results.push(result);\n return results;\n });\n };\n return PersistencePromise;\n}());\nexport { PersistencePromise };\n\n//# sourceMappingURL=persistence_promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/persistence_promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that eagerly collects documents as soon as\n * they're no longer referenced in any of its registered GarbageSources.\n *\n * This implementation keeps track of a set of keys that are potentially garbage\n * without keeping an exact reference count. During collectGarbage, the\n * collector verifies that all potential garbage keys actually have no\n * references by consulting its list of garbage sources.\n */\nvar EagerGarbageCollector = /** @class */ (function () {\n function EagerGarbageCollector() {\n this.isEager = true;\n /**\n * The garbage collectible sources to double-check during garbage collection.\n */\n this.sources = [];\n /**\n * A set of potentially garbage keys.\n * PORTING NOTE: This would be a mutable set if Javascript had one.\n */\n this.potentialGarbage = documentKeySet();\n }\n EagerGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n this.sources.push(garbageSource);\n garbageSource.setGarbageCollector(this);\n };\n EagerGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n this.sources.splice(this.sources.indexOf(garbageSource), 1);\n garbageSource.setGarbageCollector(null);\n };\n EagerGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n this.potentialGarbage = this.potentialGarbage.add(key);\n };\n EagerGarbageCollector.prototype.collectGarbage = function (txn) {\n var _this = this;\n var promises = [];\n var garbageKeys = documentKeySet();\n this.potentialGarbage.forEach(function (key) {\n var hasRefsPromise = _this.documentHasAnyReferences(txn, key);\n promises.push(hasRefsPromise.next(function (hasRefs) {\n // If there are no references, get the key.\n if (!hasRefs) {\n garbageKeys = garbageKeys.add(key);\n }\n return PersistencePromise.resolve();\n }));\n });\n // Clear locally retained potential keys and returned confirmed garbage.\n this.potentialGarbage = documentKeySet();\n return PersistencePromise.waitFor(promises).next(function () { return garbageKeys; });\n };\n EagerGarbageCollector.prototype.documentHasAnyReferences = function (txn, key) {\n var initial = PersistencePromise.resolve(false);\n return this.sources\n .map(function (source) { return function () { return source.containsKey(txn, key); }; })\n .reduce(function (promise, nextPromise) {\n return promise.next(function (result) {\n if (result) {\n return PersistencePromise.resolve(true);\n }\n else {\n return nextPromise();\n }\n });\n }, initial);\n };\n return EagerGarbageCollector;\n}());\nexport { EagerGarbageCollector };\n\n//# sourceMappingURL=eager_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/eager_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { ChangeType } from '../core/view_snapshot';\nimport { documentKeySet } from '../model/collections';\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 */\nvar LocalViewChanges = /** @class */ (function () {\n function LocalViewChanges(query, addedKeys, removedKeys) {\n this.query = query;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n LocalViewChanges.fromSnapshot = function (viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n }\n }\n return new LocalViewChanges(viewSnapshot.query, addedKeys, removedKeys);\n };\n return LocalViewChanges;\n}());\nexport { LocalViewChanges };\n\n//# sourceMappingURL=local_view_changes.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_view_changes.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\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 */\nvar ReferenceSet = /** @class */ (function () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new SortedSet(DocReference.compareByKey);\n // A set of outstanding references to a document sorted by target id.\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\n /** Keeps track of keys that have references */\n this.garbageCollector = null;\n }\n /** Returns true if the reference set contains no references. */\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.addReference(key, id); });\n };\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new DocReference(key, id));\n };\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n keys.forEach(function (key) { return _this.removeReference(key, id); });\n };\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n });\n };\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n this.refsByKey.forEach(function (ref) { return _this.removeRef(ref); });\n };\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(ref.key);\n }\n };\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n ReferenceSet.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n ReferenceSet.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(firstRef !== null && key.isEqual(firstRef.key));\n };\n return ReferenceSet;\n}());\nexport { ReferenceSet };\nvar DocReference = /** @class */ (function () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n DocReference.compareByKey = function (left, right) {\n return (DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId));\n };\n /** Compare by ID then by key */\n DocReference.compareByTargetId = function (left, right) {\n return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key));\n };\n return DocReference;\n}());\nexport { DocReference };\n\n//# sourceMappingURL=reference_set.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/reference_set.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert, fail } from './assert';\nimport * as log from './log';\nimport { Deferred } from './promise';\nimport { Code, FirestoreError } from './error';\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport var TimerId;\n(function (TimerId) {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n TimerId[\"All\"] = \"all\";\n /**\n * The following 4 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed.\n */\n TimerId[\"ListenStreamIdle\"] = \"listen_stream_idle\";\n TimerId[\"ListenStreamConnectionBackoff\"] = \"listen_stream_connection_backoff\";\n TimerId[\"WriteStreamIdle\"] = \"write_stream_idle\";\n TimerId[\"WriteStreamConnectionBackoff\"] = \"write_stream_connection_backoff\";\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n TimerId[\"OnlineStateTimeout\"] = \"online_state_timeout\";\n})(TimerId || (TimerId = {}));\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 */\nvar DelayedOperation = /** @class */ (function () {\n function DelayedOperation(asyncQueue, timerId, targetTimeMs, op, removalCallback) {\n this.asyncQueue = asyncQueue;\n this.timerId = timerId;\n this.targetTimeMs = targetTimeMs;\n this.op = op;\n this.removalCallback = removalCallback;\n this.deferred = new Deferred();\n this.then = this.deferred.promise.then.bind(this.deferred.promise);\n this.catch = this.deferred.promise.catch.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(function (err) { });\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 */\n DelayedOperation.createAndSchedule = function (asyncQueue, timerId, delayMs, op, removalCallback) {\n var targetTime = Date.now() + delayMs;\n var delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);\n delayedOp.start(delayMs);\n return delayedOp;\n };\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n DelayedOperation.prototype.start = function (delayMs) {\n var _this = this;\n this.timerHandle = setTimeout(function () { return _this.handleDelayElapsed(); }, delayMs);\n };\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n DelayedOperation.prototype.skipDelay = function () {\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 */\n DelayedOperation.prototype.cancel = function (reason) {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));\n }\n };\n DelayedOperation.prototype.handleDelayElapsed = function () {\n var _this = this;\n this.asyncQueue.enqueue(function () {\n if (_this.timerHandle !== null) {\n _this.clearTimeout();\n return _this.op().then(function (result) {\n return _this.deferred.resolve(result);\n });\n }\n else {\n return Promise.resolve();\n }\n });\n };\n DelayedOperation.prototype.clearTimeout = function () {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n };\n return DelayedOperation;\n}());\nvar AsyncQueue = /** @class */ (function () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve();\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.delayedOperations = [];\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.operationInProgress = false;\n }\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n AsyncQueue.prototype.enqueue = function (op) {\n var _this = this;\n this.verifyNotFailed();\n var newTail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op()\n .catch(function (error) {\n _this.failure = error;\n _this.operationInProgress = false;\n var message = error.stack || error.message || '';\n log.error('INTERNAL UNHANDLED ERROR: ', message);\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(function () {\n throw error;\n }, 0);\n }\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 error;\n })\n .then(function (result) {\n _this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n };\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\n * the operation prior to its running.\n */\n AsyncQueue.prototype.enqueueAfterDelay = function (timerId, delayMs, op) {\n var _this = this;\n this.verifyNotFailed();\n // While not necessarily harmful, we currently don't expect to have multiple\n // ops with the same timer id in the queue, so defensively reject them.\n assert(!this.containsDelayedOperation(timerId), \"Attempted to schedule multiple operations with timer id \" + timerId + \".\");\n var delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, function (op) { return _this.removeDelayedOperation(op); });\n this.delayedOperations.push(delayedOp);\n return delayedOp;\n };\n AsyncQueue.prototype.verifyNotFailed = function () {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message));\n }\n };\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n AsyncQueue.prototype.drain = function () {\n return this.enqueue(function () { return Promise.resolve(); });\n };\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n AsyncQueue.prototype.containsDelayedOperation = function (timerId) {\n return this.delayedOperations.findIndex(function (op) { return op.timerId === timerId; }) >= 0;\n };\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId Delayed operations up to and including this TimerId will\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\n * all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n AsyncQueue.prototype.runDelayedOperationsEarly = function (lastTimerId) {\n var _this = this;\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(function () {\n assert(lastTimerId === TimerId.All ||\n _this.containsDelayedOperation(lastTimerId), \"Attempted to drain to missing operation \" + lastTimerId);\n // Run ops in the same order they'd run if they ran naturally.\n _this.delayedOperations.sort(function (a, b) { return a.targetTimeMs - b.targetTimeMs; });\n for (var _i = 0, _a = _this.delayedOperations; _i < _a.length; _i++) {\n var op = _a[_i];\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n return _this.drain();\n });\n };\n /** Called once a DelayedOperation is run or canceled. */\n AsyncQueue.prototype.removeDelayedOperation = function (op) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n var index = this.delayedOperations.indexOf(op);\n assert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n };\n return AsyncQueue;\n}());\nexport { AsyncQueue };\n\n//# sourceMappingURL=async_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { ReferenceSet } from '../local/reference_set';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { CurrentStatusUpdate, RemoteEvent } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { isNullOrUndefined } from '../util/types';\nimport { Query } from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { TargetIdGenerator } from './target_id_generator';\nimport { AddedLimboDocument, RemovedLimboDocument, View } from './view';\nvar LOG_TAG = 'SyncEngine';\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nvar QueryView = /** @class */ (function () {\n function QueryView(\n /**\n * The query itself.\n */\n query, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n targetId, \n /**\n * An identifier from the datastore backend that indicates the last state\n * of the results that was received. This can be used to indicate where\n * to continue receiving new doc changes for the query.\n */\n resumeToken, \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 view) {\n this.query = query;\n this.targetId = targetId;\n this.resumeToken = resumeToken;\n this.view = view;\n }\n return QueryView;\n}());\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nvar SyncEngine = /** @class */ (function () {\n function SyncEngine(localStore, remoteStore, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.currentUser = currentUser;\n this.viewHandler = null;\n this.errorHandler = null;\n this.queryViewsByQuery = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\n this.limboKeysByTarget = {};\n this.limboDocumentRefs = new ReferenceSet();\n this.limboCollector = new EagerGarbageCollector();\n /** Stores user completion handlers, indexed by User and BatchId. */\n this.mutationUserCallbacks = {};\n this.targetIdGenerator = TargetIdGenerator.forSyncEngine();\n }\n /** Subscribes view and error handler. Can be called only once. */\n SyncEngine.prototype.subscribe = function (viewHandler, errorHandler) {\n assert(viewHandler !== null && errorHandler !== null, 'View and error handlers cannot be null');\n assert(this.viewHandler === null && this.errorHandler === null, 'SyncEngine already has a subscriber.');\n this.viewHandler = viewHandler;\n this.errorHandler = errorHandler;\n this.limboCollector.addGarbageSource(this.limboDocumentRefs);\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 targetId of the query.\n */\n SyncEngine.prototype.listen = function (query) {\n var _this = this;\n this.assertSubscribed('listen()');\n assert(!this.queryViewsByQuery.has(query), 'We already listen to the query: ' + query);\n return this.localStore.allocateQuery(query).then(function (queryData) {\n return _this.localStore\n .executeQuery(query)\n .then(function (docs) {\n return _this.localStore\n .remoteDocumentKeys(queryData.targetId)\n .then(function (remoteKeys) {\n var view = new View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n var viewChange = view.applyChanges(viewDocChanges);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, queryData.resumeToken, view);\n _this.queryViewsByQuery.set(query, data);\n _this.queryViewsByTarget[queryData.targetId] = data;\n _this.viewHandler([viewChange.snapshot]);\n _this.remoteStore.listen(queryData);\n });\n })\n .then(function () {\n return queryData.targetId;\n });\n });\n };\n /** Stops listening to the query. */\n SyncEngine.prototype.unlisten = function (query) {\n var _this = this;\n this.assertSubscribed('unlisten()');\n var queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n return this.localStore.releaseQuery(query).then(function () {\n _this.remoteStore.unlisten(queryView.targetId);\n return _this.removeAndCleanupQuery(queryView).then(function () {\n return _this.localStore.collectGarbage();\n });\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 */\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n this.assertSubscribed('write()');\n return this.localStore\n .localWrite(batch)\n .then(function (result) {\n _this.addMutationCallback(result.batchId, userCallback);\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n })\n .then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n };\n // TODO(klimt): Wrap the given error in a standard Firestore error object.\n SyncEngine.prototype.wrapUpdateFunctionError = function (error) {\n return error;\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 some other client has changed any of the data\n * referenced, then the updateFunction will be called again. If the\n * updateFunction still fails after the given number of retries, then the\n * transaction will be rejection.\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 *\n * The promise returned is resolved when the transaction is fully committed.\n */\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n if (retries === void 0) { retries = 5; }\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n var wrappedUpdateFunction = function () {\n try {\n var userPromise = updateFunction(transaction);\n if (isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n }\n catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n return wrappedUpdateFunction().then(function (result) {\n return transaction\n .commit()\n .then(function () {\n return result;\n })\n .catch(function (error) {\n if (retries === 0) {\n return Promise.reject(error);\n }\n // TODO(klimt): Put in a retry delay?\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n this.assertSubscribed('applyRemoteEvent()');\n // Make sure limbo documents are deleted if there were no results\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboKey = _this.limboKeysByTarget[targetId];\n if (limboKey &&\n targetChange.currentStatusUpdate ===\n CurrentStatusUpdate.MarkCurrent &&\n !remoteEvent.documentUpdates.get(limboKey)) {\n // When listening to a query the server responds with a snapshot\n // containing documents matching the query and a current marker\n // telling us we're now in sync. It's possible for these to arrive\n // as separate remote events or as a single remote event.\n // For a document query, there will be no documents sent in the\n // response if the document doesn't exist.\n //\n // If the snapshot arrives separately from the current marker,\n // we handle it normally and updateTrackedLimbos will resolve the\n // limbo status of the document, removing it from limboDocumentRefs.\n // This works because clients only initiate limbo resolution when\n // a target is current and because all current targets are\n // always at a consistent snapshot.\n //\n // However, if the document doesn't exist and the current marker\n // arrives, the document is not present in the snapshot and our\n // normal view handling would consider the document to remain in\n // limbo indefinitely because there are no updates to the document.\n // To avoid this, we specially handle this just this case here:\n // synthesizing a delete.\n //\n // TODO(dimond): Ideally we would have an explicit lookup query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n remoteEvent.addDocumentUpdate(new NoDocument(limboKey, remoteEvent.snapshotVersion));\n }\n });\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n });\n };\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState) {\n var newViewSnapshots = [];\n this.queryViewsByQuery.forEach(function (query, queryView) {\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.viewHandler(newViewSnapshots);\n };\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n var _this = this;\n this.assertSubscribed('rejectListens()');\n var limboKey = this.limboKeysByTarget[targetId];\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboKeysByTarget[targetId];\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 var docMap = new SortedMap(DocumentKey.comparator);\n docMap = docMap.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\n var event_1 = new RemoteEvent(SnapshotVersion.MIN, {}, docMap);\n return this.applyRemoteEvent(event_1);\n }\n else {\n var queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return this.localStore.releaseQuery(queryView_1.query).then(function () {\n return _this.removeAndCleanupQuery(queryView_1).then(function () {\n _this.errorHandler(queryView_1.query, err);\n });\n });\n }\n };\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n this.assertSubscribed('applySuccessfulWrite()');\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 this.processUserCallback(mutationBatchResult.batch.batchId, \n /*error=*/ null);\n return this.localStore\n .acknowledgeBatch(mutationBatchResult)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error) {\n var _this = this;\n this.assertSubscribed('rejectFailedWrite()');\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 this.processUserCallback(batchId, error);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n });\n };\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n SyncEngine.prototype.processUserCallback = function (batchId, error) {\n var newCallbacks = this.mutationUserCallbacks[this.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 (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n if (error) {\n callback.reject(error);\n }\n else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n }\n else if (limboChange instanceof RemovedLimboDocument) {\n log.debug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n }\n else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n return this.gcLimboDocuments();\n };\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n log.debug(LOG_TAG, 'New document in limbo: ' + key);\n var limboTargetId = this.targetIdGenerator.next();\n var query = Query.atPath(key.path);\n this.limboKeysByTarget[limboTargetId] = key;\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.Listen));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n };\n SyncEngine.prototype.gcLimboDocuments = function () {\n var _this = this;\n // HACK: We can use a null transaction here, because we know that the\n // reference set is entirely within memory and doesn't need a store engine.\n return this.limboCollector\n .collectGarbage(null)\n .next(function (keys) {\n keys.forEach(function (key) {\n var limboTargetId = _this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n _this.remoteStore.unlisten(limboTargetId);\n _this.limboTargetsByKey = _this.limboTargetsByKey.remove(key);\n delete _this.limboKeysByTarget[limboTargetId];\n });\n })\n .toPromise();\n };\n // Visible for testing\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n var _this = this;\n var newSnaps = [];\n var docChangesInAllViews = [];\n var queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve()\n .then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\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 return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n })\n .then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges, targetChange);\n return _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges).then(function () {\n if (viewChange.snapshot) {\n newSnaps.push(viewChange.snapshot);\n var docChanges = LocalViewChanges.fromSnapshot(viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n });\n }));\n });\n return Promise.all(queriesProcessed)\n .then(function () {\n _this.viewHandler(newSnaps);\n return _this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n })\n .then(function () {\n return _this.localStore.collectGarbage();\n });\n };\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.viewHandler !== null && this.errorHandler !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n SyncEngine.prototype.handleUserChange = function (user) {\n var _this = this;\n this.currentUser = user;\n return this.localStore\n .handleUserChange(user)\n .then(function (changes) {\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n })\n .then(function () {\n return _this.remoteStore.handleUserChange(user);\n });\n };\n return SyncEngine;\n}());\nexport { SyncEngine };\n\n//# sourceMappingURL=sync_engine.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/sync_engine.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet, documentVersionMap } from './collections';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nexport var BATCHID_UNKNOWN = -1;\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nvar MutationBatch = /** @class */ (function () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n };\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n var baseDoc = maybeDoc;\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\n }\n }\n return maybeDoc;\n };\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n return keySet;\n };\n MutationBatch.prototype.isEqual = function (other) {\n return (this.batchId === other.batchId &&\n misc.arrayEquals(this.mutations, other.mutations));\n };\n /**\n * Returns true if this mutation batch has already been removed from the\n * mutation queue.\n *\n * Note that not all implementations of the MutationQueue necessarily use\n * tombstones as part of their implementation and generally speaking no code\n * outside the mutation queues should really care about this.\n */\n MutationBatch.prototype.isTombstone = function () {\n return this.mutations.length === 0;\n };\n /** Converts this batch into a tombstone */\n MutationBatch.prototype.toTombstone = function () {\n return new MutationBatch(this.batchId, this.localWriteTime, []);\n };\n return MutationBatch;\n}());\nexport { MutationBatch };\n/** The result of applying a mutation batch to the backend. */\nvar MutationBatchResult = /** @class */ (function () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\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=>version mapping (docVersions).\n */\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n for (var i = 0; i < mutations.length; i++) {\n var version = results[i].version;\n if (version === null) {\n // deletes don't have a version, so we substitute the commitVersion\n // of the entire batch.\n version = commitVersion;\n }\n versionMap = versionMap.insert(mutations[i].key, version);\n }\n return new MutationBatchResult(batch, commitVersion, results, streamToken, versionMap);\n };\n return MutationBatchResult;\n}());\nexport { MutationBatchResult };\n\n//# sourceMappingURL=mutation_batch.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/model/mutation_batch.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbQueryCache } from './indexeddb_query_cache';\nimport { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport { ALL_STORES, createOrUpgradeDb, DbOwner, SCHEMA_VERSION } from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDb } from './simple_db';\nvar LOG_TAG = 'IndexedDbPersistence';\n/** If the owner lease is older than 5 seconds, try to take ownership. */\nvar OWNER_LEASE_MAX_AGE_MS = 5000;\n/** Refresh the owner lease every 4 seconds while owner. */\nvar OWNER_LEASE_REFRESH_INTERVAL_MS = 4000;\n/** LocalStorage location to indicate a zombied ownerId (see class comment). */\nvar ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX = 'zombiedOwnerId';\n/** Error when the owner lease cannot be acquired or is lost. */\nvar EXISTING_OWNER_ERROR_MSG = 'There is another tab open with offline' +\n ' persistence enabled. Only one such tab is allowed at a time. The' +\n ' other tab must be closed or persistence must be disabled.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * Currently the Firestore SDK only supports a single consumer of the database,\n * but browsers obviously support multiple tabs. IndexedDbPersistence ensures a\n * single consumer of the database via an \"owner lease\" stored in the database.\n *\n * On startup, IndexedDbPersistence assigns itself a random \"ownerId\" and writes\n * it to a special \"owner\" object in the database (if no entry exists already or\n * the current entry is expired). This owner lease is then verified inside every\n * transaction to ensure the lease has not been lost.\n *\n * If a tab opts not to acquire the owner lease (because there's an existing\n * non-expired owner) or loses the owner lease, IndexedDbPersistence enters a\n * failed state and all subsequent operations will automatically fail.\n *\n * The current owner regularly refreshes the owner lease with new timestamps to\n * prevent newly-opened tabs from taking over ownership.\n *\n * Additionally there is an optimization so that when a tab is closed, the owner\n * lease is released immediately (this is especially important to make sure that\n * a refreshed tab is able to immediately re-acquire the owner lease).\n * Unfortunately, IndexedDB cannot be reliably used in window.unload since it is\n * an asynchronous API. So in addition to attempting to give up the lease,\n * the owner writes its ownerId to a \"zombiedOwnerId\" entry in LocalStorage\n * which acts as an indicator that another tab should go ahead and take the\n * owner lease immediately regardless of the current lease timestamp.\n */\nvar IndexedDbPersistence = /** @class */ (function () {\n function IndexedDbPersistence(prefix, serializer) {\n this.ownerId = this.generateOwnerId();\n this.dbName = prefix + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.localStoragePrefix = prefix;\n }\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n if (!IndexedDbPersistence.isAvailable()) {\n this.persistenceError = new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n return Promise.reject(this.persistenceError);\n }\n assert(!this.started, 'IndexedDbPersistence double-started!');\n this.started = true;\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, createOrUpgradeDb)\n .then(function (db) {\n _this.simpleDb = db;\n })\n .then(function () { return _this.tryAcquireOwnerLease(); })\n .then(function () {\n _this.scheduleOwnerLeaseRefreshes();\n _this.attachWindowUnloadHook();\n });\n };\n IndexedDbPersistence.prototype.shutdown = function () {\n var _this = this;\n assert(this.started, 'IndexedDbPersistence shutdown without start!');\n this.started = false;\n this.detachWindowUnloadHook();\n this.stopOwnerLeaseRefreshes();\n return this.releaseOwnerLease().then(function () {\n _this.simpleDb.close();\n });\n };\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n return IndexedDbMutationQueue.forUser(user, this.serializer);\n };\n IndexedDbPersistence.prototype.getQueryCache = function () {\n return new IndexedDbQueryCache(this.serializer);\n };\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n return new IndexedDbRemoteDocumentCache(this.serializer);\n };\n IndexedDbPersistence.prototype.runTransaction = function (action, operation) {\n var _this = this;\n if (this.persistenceError) {\n return Promise.reject(this.persistenceError);\n }\n log.debug(LOG_TAG, 'Starting transaction:', action);\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n // Verify that we still have the owner lease as part of every transaction.\n return _this.ensureOwnerLease(txn).next(function () { return operation(txn); });\n });\n };\n IndexedDbPersistence.isAvailable = function () {\n return SimpleDb.isAvailable();\n };\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /**\n * Acquires the owner lease if there's no valid owner. Else returns a rejected\n * promise.\n */\n IndexedDbPersistence.prototype.tryAcquireOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (!_this.validOwner(dbOwner)) {\n var newDbOwner = new DbOwner(_this.ownerId, Date.now());\n log.debug(LOG_TAG, 'No valid owner. Acquiring owner lease. Current owner:', dbOwner, 'New owner:', newDbOwner);\n return store.put('owner', newDbOwner);\n }\n else {\n log.debug(LOG_TAG, 'Valid owner already. Failing. Current owner:', dbOwner);\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n });\n });\n };\n /** Checks the owner lease and deletes it if we are the current owner. */\n IndexedDbPersistence.prototype.releaseOwnerLease = function () {\n var _this = this;\n // NOTE: Don't use this.runTransaction, since it requires us to already\n // have the lease.\n return this.simpleDb.runTransaction('readwrite', [DbOwner.store], function (txn) {\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner !== null && dbOwner.ownerId === _this.ownerId) {\n log.debug(LOG_TAG, 'Releasing owner lease.');\n return store.delete('owner');\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Checks the owner lease and returns a rejected promise if we are not the\n * current owner. This should be included in every transaction to guard\n * against losing the owner lease.\n */\n IndexedDbPersistence.prototype.ensureOwnerLease = function (txn) {\n var _this = this;\n var store = txn.store(DbOwner.store);\n return store.get('owner').next(function (dbOwner) {\n if (dbOwner === null || dbOwner.ownerId !== _this.ownerId) {\n _this.persistenceError = new FirestoreError(Code.FAILED_PRECONDITION, EXISTING_OWNER_ERROR_MSG);\n return PersistencePromise.reject(_this.persistenceError);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /**\n * Returns true if the provided owner exists, has a recent timestamp, and\n * isn't zombied.\n *\n * NOTE: To determine if the owner is zombied, this method reads from\n * LocalStorage which could be mildly expensive.\n */\n IndexedDbPersistence.prototype.validOwner = function (dbOwner) {\n var now = Date.now();\n var minAcceptable = now - OWNER_LEASE_MAX_AGE_MS;\n var maxAcceptable = now;\n if (dbOwner === null) {\n return false; // no owner.\n }\n else if (dbOwner.leaseTimestampMs < minAcceptable) {\n return false; // owner lease has expired.\n }\n else if (dbOwner.leaseTimestampMs > maxAcceptable) {\n log.error('Persistence owner-lease is in the future. Discarding.', dbOwner);\n return false;\n }\n else if (dbOwner.ownerId === this.getZombiedOwnerId()) {\n return false; // owner's tab closed.\n }\n else {\n return true;\n }\n };\n /**\n * Schedules a recurring timer to update the owner lease timestamp to prevent\n * other tabs from taking the lease.\n */\n IndexedDbPersistence.prototype.scheduleOwnerLeaseRefreshes = function () {\n var _this = this;\n // NOTE: This doesn't need to be scheduled on the async queue and doing so\n // would increase the chances of us not refreshing on time if the queue is\n // backed up for some reason.\n this.ownerLeaseRefreshHandle = setInterval(function () {\n var txResult = _this.runTransaction('Refresh owner timestamp', function (txn) {\n // NOTE: We don't need to validate the current owner contents, since\n // runTransaction does that automatically.\n var store = txn.store(DbOwner.store);\n return store.put('owner', new DbOwner(_this.ownerId, Date.now()));\n });\n txResult.catch(function (reason) {\n // Probably means we lost the lease. Report the error and stop trying to\n // refresh the lease.\n log.error(reason);\n _this.stopOwnerLeaseRefreshes();\n });\n }, OWNER_LEASE_REFRESH_INTERVAL_MS);\n };\n IndexedDbPersistence.prototype.stopOwnerLeaseRefreshes = function () {\n if (this.ownerLeaseRefreshHandle) {\n clearInterval(this.ownerLeaseRefreshHandle);\n this.ownerLeaseRefreshHandle = null;\n }\n };\n /**\n * Attaches a window.unload handler that will synchronously write our\n * ownerId to a \"zombie owner id\" location in localstorage. This can be used\n * by tabs trying to acquire the lease to determine that the lease should be\n * acquired immediately even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the owner\n * lease). LocalStorage is used for this rather than IndexedDb because it is\n * a synchronous API and so can be used reliably from an unload handler.\n */\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n this.windowUnloadHandler = function () {\n // Record that we're zombied.\n _this.setZombiedOwnerId(_this.ownerId);\n // Attempt graceful shutdown (including releasing our owner lease), but\n // there's no guarantee it will complete.\n _this.shutdown();\n };\n window.addEventListener('unload', this.windowUnloadHandler);\n };\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\n * Returns any recorded \"zombied owner\" (i.e. a previous owner that became\n * zombied due to their tab closing) from LocalStorage, or null if no such\n * record exists.\n */\n IndexedDbPersistence.prototype.getZombiedOwnerId = function () {\n try {\n var zombiedOwnerId = window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());\n log.debug(LOG_TAG, 'Zombied ownerID from LocalStorage:', zombiedOwnerId);\n return zombiedOwnerId;\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to get zombie owner id.', e);\n return null;\n }\n };\n /**\n * Records a zombied owner (an owner that had its tab closed) in LocalStorage\n * or, if passed null, deletes any recorded zombied owner.\n */\n IndexedDbPersistence.prototype.setZombiedOwnerId = function (zombieOwnerId) {\n try {\n if (zombieOwnerId === null) {\n window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey());\n }\n else {\n window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(), zombieOwnerId);\n }\n }\n catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to set zombie owner id.', e);\n }\n };\n IndexedDbPersistence.prototype.zombiedOwnerLocalStorageKey = function () {\n return this.localStoragePrefix + ZOMBIE_OWNER_LOCALSTORAGE_SUFFIX;\n };\n IndexedDbPersistence.prototype.generateOwnerId = function () {\n // For convenience, just use an AutoId.\n return AutoId.newId();\n };\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}());\nexport { IndexedDbPersistence };\n\n//# sourceMappingURL=indexeddb_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/indexeddb_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { documentKeySet, documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { fail } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\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 */\nvar LocalDocumentsView = /** @class */ (function () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(function (remoteDoc) {\n return _this.computeLocalDocument(transaction, key, remoteDoc);\n });\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 */\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return results; });\n };\n /** Performs a query against the local view of all documents. */\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n }\n else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n });\n };\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this;\n // Query the remote documents and overlay mutations.\n // TODO(mikelehen): There may be significant overlap between the mutations\n // affecting these remote documents and the\n // getAllMutationBatchesAffectingQuery() mutations. Consider optimizing.\n var results;\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query)\n .next(function (queryResults) {\n return _this.computeLocalDocuments(transaction, queryResults);\n })\n .next(function (promisedResults) {\n results = promisedResults;\n // Now use the mutation queue to discover any other documents that may\n // match the query after applying mutations.\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n })\n .next(function (matchingMutationBatches) {\n var matchingKeys = documentKeySet();\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n // TODO(mikelehen): PERF: Check if this mutation actually\n // affects the query to reduce work.\n if (!results.get(mutation.key)) {\n matchingKeys = matchingKeys.add(mutation.key);\n }\n }\n }\n // Now add in the results for the matchingKeys.\n var promises = [];\n matchingKeys.forEach(function (key) {\n promises.push(_this.getDocument(transaction, key).next(function (doc) {\n if (doc instanceof Document) {\n results = results.insert(doc.key, doc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises);\n })\n .next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n /**\n * Takes a remote document and applies local mutations to generate the local\n * view of the document.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the document (necessary when remoteDocument\n * is null).\n * @param document The base remote document to apply mutations to or null.\n */\n LocalDocumentsView.prototype.computeLocalDocument = function (transaction, documentKey, document) {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, documentKey)\n .next(function (batches) {\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n document = batch.applyToLocalView(documentKey, document);\n }\n return document;\n });\n };\n /**\n * Takes a set of remote documents and applies local mutations to generate the\n * local view of the documents.\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documents The base remote documents to apply mutations to.\n * @return The local view of the documents.\n */\n LocalDocumentsView.prototype.computeLocalDocuments = function (transaction, documents) {\n var _this = this;\n var promises = [];\n documents.forEach(function (key, doc) {\n promises.push(_this.computeLocalDocument(transaction, key, doc).next(function (mutatedDoc) {\n if (mutatedDoc instanceof Document) {\n documents = documents.insert(mutatedDoc.key, mutatedDoc);\n }\n else if (mutatedDoc instanceof NoDocument) {\n documents = documents.remove(mutatedDoc.key);\n }\n else {\n fail('Unknown MaybeDocument: ' + mutatedDoc);\n }\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () { return documents; });\n };\n return LocalDocumentsView;\n}());\nexport { LocalDocumentsView };\n\n//# sourceMappingURL=local_documents_view.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_documents_view.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistencePromise } from './persistence_promise';\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 * NOTE: This class was introduced in iOS to work around a limitation in\n * LevelDB. Given IndexedDb has full transaction support with\n * read-your-own-writes capability, this class is not technically needed, but\n * has been preserved as a convenience and to aid portability.\n */\nvar RemoteDocumentChangeBuffer = /** @class */ (function () {\n function RemoteDocumentChangeBuffer(remoteDocumentCache) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.changes = maybeDocumentMap();\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n };\n // NOTE: removeEntry() is not presently necessary and so is omitted.\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 * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n if (bufferedEntry) {\n return PersistencePromise.resolve(bufferedEntry);\n }\n else {\n return this.remoteDocumentCache.getEntry(transaction, documentKey);\n }\n };\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var _this = this;\n var changes = this.assertChanges();\n var promises = [];\n changes.forEach(function (key, maybeDoc) {\n promises.push(_this.remoteDocumentCache.addEntry(transaction, maybeDoc));\n });\n // We should not be used to buffer any more changes.\n this.changes = null;\n return PersistencePromise.waitFor(promises);\n };\n /** Helper to assert this.changes is not null and return it. */\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n return RemoteDocumentChangeBuffer;\n}());\nexport { RemoteDocumentChangeBuffer };\n\n//# sourceMappingURL=remote_document_change_buffer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/remote_document_change_buffer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { Timestamp } from '../core/timestamp';\nimport { documentKeySet } from '../model/collections';\nimport { BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { ResetMapping, UpdateMapping } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { QueryData, QueryPurpose } from './query_data';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nvar LOG_TAG = 'LocalStore';\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nvar LocalStore = /** @class */ (function () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser, \n /**\n * The garbage collector collects documents that should no longer be\n * cached (e.g. if they are no longer retained by the above reference sets\n * and the garbage collector is performing eager collection).\n */\n garbageCollector) {\n this.persistence = persistence;\n this.garbageCollector = garbageCollector;\n /**\n * The set of document references maintained by any local views.\n */\n this.localViewReferences = new ReferenceSet();\n /** Maps a targetID to data about its query. */\n this.targetIds = {};\n /** Used to generate targetIDs for queries tracked locally. */\n this.targetIdGenerator = TargetIdGenerator.forLocalStore();\n /**\n * A heldBatchResult is a mutation batch result (from a write acknowledgement)\n * that arrived before the watch stream got notified of a snapshot that\n * includes the write. So we \"hold\" it until the watch stream catches up. It\n * ensures that the local write remains visible (latency compensation) and\n * doesn't temporarily appear reverted because the watch stream is slower than\n * the write stream and so wasn't reflecting it.\n *\n * NOTE: Eventually we want to move this functionality into the remote store.\n */\n this.heldBatchResults = [];\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n this.garbageCollector.addGarbageSource(this.localViewReferences);\n this.garbageCollector.addGarbageSource(this.queryCache);\n this.garbageCollector.addGarbageSource(this.mutationQueue);\n }\n /** Performs any initial startup actions required by the local store. */\n LocalStore.prototype.start = function () {\n var _this = this;\n return this.persistence.runTransaction('Start LocalStore', function (txn) {\n return _this.startMutationQueue(txn).next(function () { return _this.startQueryCache(txn); });\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 LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n return this.persistence.runTransaction('Handle user change', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue\n .getAllMutationBatches(txn)\n .next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.garbageCollector.removeGarbageSource(_this.mutationQueue);\n _this.mutationQueue = _this.persistence.getMutationQueue(user);\n _this.garbageCollector.addGarbageSource(_this.mutationQueue);\n return _this.startMutationQueue(txn);\n })\n .next(function () {\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n })\n .next(function (newBatches) {\n // Union the old/new changed keys.\n var changedKeys = documentKeySet();\n for (var _i = 0, _a = [oldBatches, newBatches]; _i < _a.length; _i++) {\n var batches = _a[_i];\n for (var _b = 0, batches_1 = batches; _b < batches_1.length; _b++) {\n var batch = batches_1[_b];\n for (var _c = 0, _d = batch.mutations; _c < _d.length; _c++) {\n var mutation = _d[_c];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n }\n // Return the set of all (potentially) changed documents as the\n // result of the user change.\n return _this.localDocuments.getDocuments(txn, changedKeys);\n });\n });\n };\n LocalStore.prototype.startQueryCache = function (txn) {\n var _this = this;\n return this.queryCache.start(txn).next(function () {\n var targetId = _this.queryCache.getHighestTargetId();\n _this.targetIdGenerator = TargetIdGenerator.forLocalStore(targetId);\n });\n };\n LocalStore.prototype.startMutationQueue = function (txn) {\n var _this = this;\n return this.mutationQueue\n .start(txn)\n .next(function () {\n // If we have any leftover mutation batch results from a prior run,\n // just drop them.\n // TODO(http://b/33446471): We probably need to repopulate\n // heldBatchResults or similar instead, but that is not\n // straightforward since we're not persisting the write ack versions.\n _this.heldBatchResults = [];\n return _this.mutationQueue.getHighestAcknowledgedBatchId(txn);\n })\n .next(function (highestAck) {\n // TODO(mikelehen): This is the only usage of\n // getAllMutationBatchesThroughBatchId(). Consider removing it in\n // favor of a getAcknowledgedBatches() method.\n if (highestAck !== BATCHID_UNKNOWN) {\n return _this.mutationQueue.getAllMutationBatchesThroughBatchId(txn, highestAck);\n }\n else {\n return PersistencePromise.resolve([]);\n }\n })\n .next(function (ackedBatches) {\n if (ackedBatches.length > 0) {\n return _this.mutationQueue.removeMutationBatches(txn, ackedBatches);\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n return this.persistence.runTransaction('Locally write mutations', function (txn) {\n var batch;\n var localWriteTime = Timestamp.now();\n return _this.mutationQueue\n .addMutationBatch(txn, localWriteTime, mutations)\n .next(function (promisedBatch) {\n batch = promisedBatch;\n // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n })\n .next(function (changedDocuments) {\n return { batchId: batch.batchId, changes: changedDocuments };\n });\n });\n };\n /**\n * Acknowledge 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 */\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n return this.persistence.runTransaction('Acknowledge batch', function (txn) {\n var affected;\n return _this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(function () {\n if (_this.shouldHoldBatchResult(batchResult.commitVersion)) {\n _this.heldBatchResults.push(batchResult);\n affected = documentKeySet();\n return PersistencePromise.resolve();\n }\n else {\n var documentBuffer_1 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseBatchResults(txn, [batchResult], documentBuffer_1).next(function (promisedAffectedKeys) {\n affected = promisedAffectedKeys;\n return documentBuffer_1.apply(txn);\n });\n }\n })\n .next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n return this.persistence.runTransaction('Reject batch', function (txn) {\n var toReject;\n var affectedKeys;\n return _this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next(function (promisedToReject) {\n assert(promisedToReject != null, 'Attempt to reject nonexistent batch!');\n toReject = promisedToReject;\n return _this.mutationQueue\n .getHighestAcknowledgedBatchId(txn)\n .next(function (lastAcked) {\n assert(batchId > lastAcked, \"Acknowledged batches can't be rejected.\");\n return toReject;\n });\n })\n .next(function () {\n return _this.removeMutationBatch(txn, toReject);\n })\n .next(function (promisedAffectedKeys) {\n affectedKeys = promisedAffectedKeys;\n return _this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n return this.persistence.runTransaction('Get last stream token', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n return this.persistence.runTransaction('Set last stream token', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\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 */\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n return this.queryCache.getLastRemoteSnapshotVersion();\n };\n /**\n * Update 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 */\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n var documentBuffer = new RemoteDocumentChangeBuffer(this.remoteDocuments);\n return this.persistence.runTransaction('Apply remote event', function (txn) {\n var promises = [];\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.targetIds[targetId];\n if (!queryData)\n return;\n var mapping = change.mapping;\n if (mapping) {\n // First make sure that all references are deleted\n if (mapping instanceof ResetMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeysForTargetId(txn, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.documents, targetId);\n }));\n }\n else if (mapping instanceof UpdateMapping) {\n promises.push(_this.queryCache\n .removeMatchingKeys(txn, mapping.removedDocuments, targetId)\n .next(function () {\n return _this.queryCache.addMatchingKeys(txn, mapping.addedDocuments, targetId);\n }));\n }\n else {\n return fail('Unknown mapping type: ' + JSON.stringify(mapping));\n }\n }\n // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n var resumeToken = change.resumeToken;\n if (resumeToken.length > 0) {\n queryData = queryData.update({\n resumeToken: resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n _this.targetIds[targetId] = queryData;\n promises.push(_this.queryCache.updateQueryData(txn, queryData));\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // Make sure we don't apply an old document version to the remote\n // cache, though we make an exception for SnapshotVersion.MIN which\n // can happen for manufactured events (e.g. in the case of a limbo\n // document resolution failing).\n if (existingDoc == null ||\n doc.version.isEqual(SnapshotVersion.MIN) ||\n doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n }\n else {\n log.debug(LOG_TAG, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n // The document might be garbage because it was unreferenced by\n // everything. Make sure to mark it as garbage if it is...\n _this.garbageCollector.addPotentialGarbageKey(key);\n }));\n });\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 var lastRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion();\n var remoteVersion = remoteEvent.snapshotVersion;\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteVersion);\n promises.push(_this.queryCache.setLastRemoteSnapshotVersion(txn, remoteVersion));\n }\n var releasedWriteKeys;\n return PersistencePromise.waitFor(promises)\n .next(function () { return _this.releaseHeldBatchResults(txn, documentBuffer); })\n .next(function (promisedReleasedWriteKeys) {\n releasedWriteKeys = promisedReleasedWriteKeys;\n return documentBuffer.apply(txn);\n })\n .next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys.unionWith(releasedWriteKeys));\n });\n });\n };\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n return this.persistence.runTransaction('Notify local view changes', function (txn) {\n var promises = [];\n var _loop_1 = function (view) {\n promises.push(_this.queryCache\n .getQueryData(txn, view.query)\n .next(function (queryData) {\n assert(queryData !== null, 'Local view changes contain unallocated query.');\n var targetId = queryData.targetId;\n _this.localViewReferences.addReferences(view.addedKeys, targetId);\n _this.localViewReferences.removeReferences(view.removedKeys, targetId);\n }));\n };\n for (var _i = 0, viewChanges_1 = viewChanges; _i < viewChanges_1.length; _i++) {\n var view = viewChanges_1[_i];\n _loop_1(view);\n }\n return PersistencePromise.waitFor(promises);\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 */\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n return this.persistence.runTransaction('Get next mutation batch', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n return this.persistence.runTransaction('read document', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\n * Assigns the given query an internal ID so that its results can be pinned so\n * they don't get GC'd. A query must be allocated in the local store before\n * the store can be used to manage its view.\n */\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Allocate query', function (txn) {\n var queryData;\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return PersistencePromise.resolve();\n }\n else {\n var targetId = _this.targetIdGenerator.next();\n queryData = new QueryData(query, targetId, QueryPurpose.Listen);\n return _this.queryCache.addQueryData(txn, queryData);\n }\n })\n .next(function () {\n assert(!_this.targetIds[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.targetIds[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /** Unpin all the documents associated with the given query. */\n LocalStore.prototype.releaseQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Release query', function (txn) {\n return _this.queryCache\n .getQueryData(txn, query)\n .next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n _this.localViewReferences.removeReferencesForId(queryData.targetId);\n delete _this.targetIds[queryData.targetId];\n if (_this.garbageCollector.isEager) {\n return _this.queryCache.removeQueryData(txn, queryData);\n }\n else {\n return PersistencePromise.resolve();\n }\n })\n .next(function () {\n // If this was the last watch target, then we won't get any more\n // watch snapshots, so we should release any held batch results.\n if (objUtils.isEmpty(_this.targetIds)) {\n var documentBuffer_2 = new RemoteDocumentChangeBuffer(_this.remoteDocuments);\n return _this.releaseHeldBatchResults(txn, documentBuffer_2).next(function () {\n documentBuffer_2.apply(txn);\n });\n }\n else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\n * Runs the specified query against all the documents in the local store and\n * returns the results.\n */\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n return this.persistence.runTransaction('Execute query', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n return this.persistence.runTransaction('Remote document keys', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n };\n /**\n * Collect garbage if necessary.\n * Should be called periodically by Sync Engine to recover resources. The\n * implementation must guarantee that GC won't happen in other places than\n * this method call.\n */\n LocalStore.prototype.collectGarbage = function () {\n var _this = this;\n // Call collectGarbage regardless of whether isGCEnabled so the referenceSet\n // doesn't continue to accumulate the garbage keys.\n return this.persistence.runTransaction('Garbage collection', function (txn) {\n return _this.garbageCollector.collectGarbage(txn).next(function (garbage) {\n var promises = [];\n garbage.forEach(function (key) {\n promises.push(_this.remoteDocuments.removeEntry(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n });\n });\n };\n LocalStore.prototype.releaseHeldBatchResults = function (txn, documentBuffer) {\n var toRelease = [];\n for (var _i = 0, _a = this.heldBatchResults; _i < _a.length; _i++) {\n var batchResult = _a[_i];\n if (!this.isRemoteUpToVersion(batchResult.commitVersion)) {\n break;\n }\n toRelease.push(batchResult);\n }\n if (toRelease.length === 0) {\n return PersistencePromise.resolve(documentKeySet());\n }\n else {\n this.heldBatchResults.splice(0, toRelease.length);\n return this.releaseBatchResults(txn, toRelease, documentBuffer);\n }\n };\n LocalStore.prototype.isRemoteUpToVersion = function (version) {\n // If there are no watch targets, then we won't get remote snapshots, and\n // we are always \"up-to-date.\"\n var lastRemoteVersion = this.queryCache.getLastRemoteSnapshotVersion();\n return (version.compareTo(lastRemoteVersion) <= 0 ||\n objUtils.isEmpty(this.targetIds));\n };\n LocalStore.prototype.shouldHoldBatchResult = function (version) {\n // Check if watcher isn't up to date or prior results are already held.\n return (!this.isRemoteUpToVersion(version) || this.heldBatchResults.length > 0);\n };\n LocalStore.prototype.releaseBatchResults = function (txn, batchResults, documentBuffer) {\n var _this = this;\n var promiseChain = PersistencePromise.resolve();\n var _loop_2 = function (batchResult) {\n promiseChain = promiseChain.next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n });\n };\n for (var _i = 0, batchResults_1 = batchResults; _i < batchResults_1.length; _i++) {\n var batchResult = batchResults_1[_i];\n _loop_2(batchResult);\n }\n return promiseChain.next(function () {\n return _this.removeMutationBatches(txn, batchResults.map(function (result) { return result.batch; }));\n });\n };\n LocalStore.prototype.removeMutationBatch = function (txn, batch) {\n return this.removeMutationBatches(txn, [batch]);\n };\n /** Removes all the mutation batches named in the given array. */\n LocalStore.prototype.removeMutationBatches = function (txn, batches) {\n var affectedDocs = documentKeySet();\n for (var _i = 0, batches_2 = batches; _i < batches_2.length; _i++) {\n var batch = batches_2[_i];\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n affectedDocs = affectedDocs.add(key);\n }\n }\n return this.mutationQueue\n .removeMutationBatches(txn, batches)\n .next(function () { return affectedDocs; });\n };\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain\n .next(function () {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null');\n }\n else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain;\n };\n return LocalStore;\n}());\nexport { LocalStore };\n\n//# sourceMappingURL=local_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/local_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\nimport { PersistencePromise } from './persistence_promise';\nimport { DocReference } from './reference_set';\nvar MemoryMutationQueue = /** @class */ (function () {\n function MemoryMutationQueue() {\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.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n this.lastStreamToken = emptyByteString();\n /** The garbage collector to notify about potential garbage keys. */\n this.garbageCollector = null;\n /** An ordered mapping between documents and the mutations batch IDs. */\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n }\n MemoryMutationQueue.prototype.start = function (transaction) {\n // NOTE: The queue may be shutdown / started multiple times, since we\n // maintain the queue for the duration of the app session in case a user\n // logs out / back in. To behave like the LevelDB-backed MutationQueue (and\n // accommodate tests that expect as much), we reset nextBatchId and\n // highestAcknowledgedBatchId if the queue is empty.\n if (this.mutationQueue.length === 0) {\n this.nextBatchId = 1;\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n }\n assert(this.highestAcknowledgedBatchId < this.nextBatchId, 'highestAcknowledgedBatchId must be less than the nextBatchId');\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n MemoryMutationQueue.prototype.getNextBatchId = function (transaction) {\n return PersistencePromise.resolve(this.nextBatchId);\n };\n MemoryMutationQueue.prototype.getHighestAcknowledgedBatchId = function (transaction) {\n return PersistencePromise.resolve(this.highestAcknowledgedBatchId);\n };\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n // Verify that the batch in the queue is the one to be acknowledged.\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId);\n assert(!check.isTombstone(), \"Can't acknowledge a previously removed batch\");\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.lastStreamToken);\n };\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch);\n // Track references by document key.\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\n }\n return PersistencePromise.resolve(batch);\n };\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var size = this.mutationQueue.length;\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, this.highestAcknowledgedBatchId) + 1;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n var rawIndex = this.indexOfBatchId(nextBatchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n // Finally return the first non-tombstone batch.\n for (; index < size; index++) {\n var batch = this.mutationQueue[index];\n if (!batch.isTombstone()) {\n return PersistencePromise.resolve(batch);\n }\n }\n return PersistencePromise.resolve(null);\n };\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesThroughBatchId = function (transaction, batchId) {\n var count = this.mutationQueue.length;\n var endIndex = this.indexOfBatchId(batchId);\n if (endIndex < 0) {\n endIndex = 0;\n }\n else if (endIndex >= count) {\n endIndex = count;\n }\n else {\n // The endIndex is in the queue so increment to pull everything in the\n // queue including it.\n endIndex++;\n }\n return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(endIndex));\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n var start = new DocReference(documentKey, 0);\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.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 var startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n var start = new DocReference(new DocumentKey(startPath), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n }\n else {\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 if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\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 var result = [];\n uniqueBatchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return PersistencePromise.resolve(result);\n };\n MemoryMutationQueue.prototype.removeMutationBatches = function (transaction, batches) {\n var batchCount = batches.length;\n assert(batchCount > 0, 'Should not remove mutations when none exist.');\n var firstBatchId = batches[0].batchId;\n var queueCount = this.mutationQueue.length;\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n var startIndex = this.indexOfExistingBatchId(firstBatchId, 'removed');\n assert(this.mutationQueue[startIndex].batchId === firstBatchId, 'Removed batches must exist in the queue');\n // Check that removed batches are contiguous (while excluding tombstones).\n var batchIndex = 1;\n var queueIndex = startIndex + 1;\n while (batchIndex < batchCount && queueIndex < queueCount) {\n var batch = this.mutationQueue[queueIndex];\n if (batch.isTombstone()) {\n queueIndex++;\n continue;\n }\n assert(batch.batchId === batches[batchIndex].batchId, 'Removed batches must be contiguous in the queue');\n batchIndex++;\n queueIndex++;\n }\n // Only actually remove batches if removing at the front of the queue.\n // Previously rejected batches may have left tombstones in the queue, so\n // expand the removal range to include any tombstones.\n if (startIndex === 0) {\n for (; queueIndex < queueCount; queueIndex++) {\n var batch = this.mutationQueue[queueIndex];\n if (!batch.isTombstone()) {\n break;\n }\n }\n var length_1 = queueIndex - startIndex;\n this.mutationQueue.splice(startIndex, length_1);\n }\n else {\n // Mark the tombstones\n for (var i = startIndex; i < queueIndex; i++) {\n this.mutationQueue[i] = this.mutationQueue[i].toTombstone();\n }\n }\n var references = this.batchesByDocumentKey;\n for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {\n var batch = batches_1[_i];\n var batchId = batch.batchId;\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key;\n if (this.garbageCollector !== null) {\n this.garbageCollector.addPotentialGarbageKey(key);\n }\n var ref = new DocReference(key, batchId);\n references = references.delete(ref);\n }\n }\n this.batchesByDocumentKey = references;\n return PersistencePromise.resolve();\n };\n MemoryMutationQueue.prototype.setGarbageCollector = function (garbageCollector) {\n this.garbageCollector = garbageCollector;\n };\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n };\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n return PersistencePromise.resolve();\n };\n /**\n * A private helper that collects all the mutations batches in the queue up to\n * but not including the given endIndex. All tombstones in the queue are\n * excluded.\n */\n MemoryMutationQueue.prototype.getAllLiveMutationBatchesBeforeIndex = function (endIndex) {\n var result = [];\n for (var i = 0; i < endIndex; i++) {\n var batch = this.mutationQueue[i];\n if (!batch.isTombstone()) {\n result.push(batch);\n }\n }\n return result;\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 */\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return 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 */\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\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 var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\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 */\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch.isTombstone() ? null : batch;\n };\n return MemoryMutationQueue;\n}());\nexport { MemoryMutationQueue };\n\n//# sourceMappingURL=memory_mutation_queue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_mutation_queue.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ObjectMap } from '../util/obj_map';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { assert } from '../util/assert';\nvar MemoryQueryCache = /** @class */ (function () {\n function MemoryQueryCache() {\n /**\n * Maps a query to the data about that query\n */\n this.queries = new ObjectMap(function (q) { return q.canonicalId(); });\n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.references = new ReferenceSet();\n this.targetCount = 0;\n }\n MemoryQueryCache.prototype.start = function (transaction) {\n // Nothing to do.\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function () {\n return this.lastRemoteSnapshotVersion;\n };\n MemoryQueryCache.prototype.getHighestTargetId = function () {\n return this.highestTargetId;\n };\n MemoryQueryCache.prototype.setLastRemoteSnapshotVersion = function (transaction, snapshotVersion) {\n this.lastRemoteSnapshotVersion = snapshotVersion;\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.saveQueryData = function (queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n // TODO(GC): track sequence number\n };\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n assert(!this.queries.has(queryData.query), 'Adding a query that already exists');\n this.saveQueryData(queryData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n assert(this.queries.has(queryData.query), 'Updating a non-existent query');\n this.saveQueryData(queryData);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\n assert(this.queries.has(queryData.query), 'Removing a non-existent target from the cache');\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n };\n Object.defineProperty(MemoryQueryCache.prototype, \"count\", {\n get: function () {\n return this.targetCount;\n },\n enumerable: true,\n configurable: true\n });\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return PersistencePromise.resolve(queryData);\n };\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n };\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n };\n MemoryQueryCache.prototype.setGarbageCollector = function (gc) {\n this.references.setGarbageCollector(gc);\n };\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return this.references.containsKey(txn, key);\n };\n return MemoryQueryCache;\n}());\nexport { MemoryQueryCache };\n\n//# sourceMappingURL=memory_query_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_query_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentMap, maybeDocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { PersistencePromise } from './persistence_promise';\nvar MemoryRemoteDocumentCache = /** @class */ (function () {\n function MemoryRemoteDocumentCache() {\n this.docs = maybeDocumentMap();\n }\n MemoryRemoteDocumentCache.prototype.addEntry = function (transaction, maybeDocument) {\n this.docs = this.docs.insert(maybeDocument.key, maybeDocument);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n this.docs = this.docs.remove(documentKey);\n return PersistencePromise.resolve();\n };\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n return PersistencePromise.resolve(this.docs.get(documentKey));\n };\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap();\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 var prefix = new DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n var _a = iterator.getNext(), key = _a.key, maybeDoc = _a.value;\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }\n return PersistencePromise.resolve(results);\n };\n return MemoryRemoteDocumentCache;\n}());\nexport { MemoryRemoteDocumentCache };\n\n//# sourceMappingURL=memory_remote_document_cache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_remote_document_cache.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { assert } from '../util/assert';\nimport { debug } from '../util/log';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport { MemoryQueryCache } from './memory_query_cache';\nimport { MemoryRemoteDocumentCache } from './memory_remote_document_cache';\nvar LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nvar MemoryPersistence = /** @class */ (function () {\n function MemoryPersistence() {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n this.mutationQueues = {};\n this.remoteDocumentCache = new MemoryRemoteDocumentCache();\n this.queryCache = new MemoryQueryCache();\n this.started = false;\n }\n MemoryPersistence.prototype.start = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // No durable state to read on startup.\n assert(!this.started, 'MemoryPersistence double-started!');\n this.started = true;\n return [2 /*return*/];\n });\n });\n };\n MemoryPersistence.prototype.shutdown = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // No durable state to ensure is closed on shutdown.\n assert(this.started, 'MemoryPersistence shutdown without start!');\n this.started = false;\n return [2 /*return*/];\n });\n });\n };\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue();\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n };\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n MemoryPersistence.prototype.runTransaction = function (action, operation) {\n debug(LOG_TAG, 'Starting transaction:', action);\n return operation(new MemoryPersistenceTransaction()).toPromise();\n };\n return MemoryPersistence;\n}());\nexport { MemoryPersistence };\n/** Dummy class since memory persistence doesn't actually use transactions. */\nvar MemoryPersistenceTransaction = /** @class */ (function () {\n function MemoryPersistenceTransaction() {\n }\n return MemoryPersistenceTransaction;\n}());\n\n//# sourceMappingURL=memory_persistence.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/memory_persistence.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { documentKeySet } from '../model/collections';\nimport { PersistencePromise } from './persistence_promise';\n/**\n * A garbage collector implementation that does absolutely nothing. It ignores\n * all addGarbageSource and addPotentialGarbageKey messages and and never\n * produces any garbage.\n */\nvar NoOpGarbageCollector = /** @class */ (function () {\n function NoOpGarbageCollector() {\n this.isEager = false;\n }\n NoOpGarbageCollector.prototype.addGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.removeGarbageSource = function (garbageSource) {\n // Not tracking garbage so don't track sources.\n };\n NoOpGarbageCollector.prototype.addPotentialGarbageKey = function (key) {\n // Not tracking garbage so ignore.\n };\n NoOpGarbageCollector.prototype.collectGarbage = function (txn) {\n return PersistencePromise.resolve(documentKeySet());\n };\n return NoOpGarbageCollector;\n}());\nexport { NoOpGarbageCollector };\n\n//# sourceMappingURL=no_op_garbage_collector.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/local/no_op_garbage_collector.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n return Deferred;\n}());\nexport { Deferred };\n/**\n * Takes an array of values and sequences them using the promise (or value)\n * returned by the supplied callback. The callback for each item is called\n * after the promise is resolved for the previous item.\n * The function returns a promise which is resolved after the promise for\n * the last item is resolved.\n */\nexport function sequence(values, fn, initialValue) {\n var result = Promise.resolve(initialValue);\n values.forEach(function (value) {\n result = result.then(function (lastResult) { return fn(value, lastResult); });\n });\n return result;\n}\n\n//# sourceMappingURL=promise.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/promise.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { assert } from '../util/assert';\nimport { TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { ExponentialBackoff } from './backoff';\nimport { isNullOrUndefined } from '../util/types';\nvar LOG_TAG = 'PersistentStream';\nvar PersistentStreamState;\n(function (PersistentStreamState) {\n /**\n * The streaming RPC is not running and there's no error condition.\n * Calling `start` will start the stream immediately without backoff.\n * While in this state isStarted will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\n * The stream is starting, and is waiting for an auth token to attach to\n * the initial request. While in this state, isStarted will return\n * true but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Auth\"] = 1] = \"Auth\";\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted and isOpen will return true.\n */\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n *\n */\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After\n * waiting is complete, the stream will try to open. While in this\n * state isStarted() will return YES but isOpen will return false.\n */\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n /**\n * The stream has been explicitly stopped; no further events will be emitted.\n */\n PersistentStreamState[PersistentStreamState[\"Stopped\"] = 5] = \"Stopped\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\n/** The time a stream stays open after it is marked idle. */\nvar IDLE_TIMEOUT_MS = 60 * 1000;\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 *\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\n * onClose 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 */\nvar PersistentStream = /** @class */ (function () {\n function PersistentStream(queue, connectionTimerId, idleTimerId, connection, credentialsProvider) {\n this.queue = queue;\n this.idleTimerId = idleTimerId;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.inactivityTimerPromise = null;\n this.stream = null;\n this.listener = null;\n this.backoff = new ExponentialBackoff(queue, connectionTimerId, BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n this.state = PersistentStreamState.Initial;\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 */\n PersistentStream.prototype.isStarted = function () {\n return (this.state === PersistentStreamState.Backoff ||\n this.state === PersistentStreamState.Auth ||\n this.state === PersistentStreamState.Open);\n };\n /**\n * Returns true if the underlying RPC is open (the openHandler has been\n * called) and the stream is ready for outbound requests.\n */\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\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 ready\n * for outbound requests, at which point isOpen will return true.\n *\n * When start returns, isStarted will return true.\n */\n PersistentStream.prototype.start = function (listener) {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff(listener);\n return;\n }\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.listener = listener;\n this.auth();\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 */\n PersistentStream.prototype.stop = function () {\n if (this.isStarted()) {\n this.close(PersistentStreamState.Stopped);\n }\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 function. That function can decide to\n * inhibit backoff if required.\n */\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.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 */\n PersistentStream.prototype.markIdle = function () {\n var _this = this;\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 if (this.isOpen() && this.inactivityTimerPromise === null) {\n this.inactivityTimerPromise = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, function () { return _this.handleIdleCloseTimer(); });\n }\n };\n /** Sends a message to the underlying stream. */\n PersistentStream.prototype.sendRequest = function (msg) {\n this.cancelIdleCheck();\n this.stream.send(msg);\n };\n /** Called by the idle timer when the stream should close due to inactivity. */\n PersistentStream.prototype.handleIdleCloseTimer = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (this.isOpen()) {\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 [2 /*return*/, this.close(PersistentStreamState.Initial)];\n }\n return [2 /*return*/];\n });\n });\n };\n /** Marks the stream as active again. */\n PersistentStream.prototype.cancelIdleCheck = function () {\n if (this.inactivityTimerPromise) {\n this.inactivityTimerPromise.cancel();\n this.inactivityTimerPromise = null;\n }\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` unless `finalState` is set to\n * `PersistentStreamState.Stopped`.\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */\n PersistentStream.prototype.close = function (finalState, error) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var listener;\n return tslib_1.__generator(this, function (_a) {\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error), \"Can't provide an error when not in an error state.\");\n // The stream will be closed so we don't need our idle close timer anymore.\n this.cancelIdleCheck();\n // Ensure we don't leave a pending backoff operation queued (in case close()\n // was called while we were waiting to reconnect).\n this.backoff.cancel();\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n }\n else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log.error(error.toString());\n log.error('Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n }\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\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 = finalState;\n listener = this.listener;\n // Clear the listener to avoid bleeding of events from the underlying streams.\n this.listener = null;\n // If the caller explicitly requested a stream stop, don't notify them of a closing stream (it\n // could trigger undesirable recovery logic, etc.).\n if (finalState !== PersistentStreamState.Stopped) {\n return [2 /*return*/, listener.onClose(error)];\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n PersistentStream.prototype.tearDown = function () { };\n PersistentStream.prototype.auth = function () {\n var _this = this;\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Auth;\n this.credentialsProvider.getToken(/*forceRefresh=*/ false).then(function (token) {\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.startStream(token);\n }, function (error) {\n _this.queue.enqueue(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var rpcError;\n return tslib_1.__generator(this, function (_a) {\n if (this.state !== PersistentStreamState.Stopped) {\n rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message);\n return [2 /*return*/, this.handleStreamClose(rpcError)];\n }\n return [2 /*return*/];\n });\n }); });\n });\n };\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n if (this.state === PersistentStreamState.Stopped) {\n // Stream can be stopped while waiting for authorization.\n return;\n }\n assert(this.state === PersistentStreamState.Auth, 'Trying to start stream in a non-auth state');\n // Helper function to dispatch to AsyncQueue and make sure that any\n // close will seem instantaneous and events are prevented from being\n // raised after the close call\n var dispatchIfStillActive = function (stream, fn) {\n _this.queue.enqueue(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // Only raise events if the stream instance has not changed\n if (this.stream === stream) {\n return [2 /*return*/, fn()];\n }\n return [2 /*return*/];\n });\n }); });\n };\n // Only start stream if listener has not changed\n if (this.listener !== null) {\n var currentStream_1 = this.startRpc(token);\n this.stream = currentStream_1;\n this.stream.onOpen(function () {\n dispatchIfStillActive(currentStream_1, function () {\n assert(_this.state === PersistentStreamState.Auth, 'Expected stream to be in state auth, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.handleStreamClose(error);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfStillActive(currentStream_1, function () {\n return _this.onMessage(msg);\n });\n });\n }\n };\n PersistentStream.prototype.performBackoff = function (listener) {\n var _this = this;\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff in an error case');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndRun(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (this.state === PersistentStreamState.Stopped) {\n // We should have canceled the backoff timer when the stream was\n // closed, but just in case we make this a no-op.\n return [2 /*return*/];\n }\n this.state = PersistentStreamState.Initial;\n this.start(listener);\n assert(this.isStarted(), 'PersistentStream should have started');\n return [2 /*return*/];\n });\n }); });\n };\n PersistentStream.prototype.handleStreamClose = function (error) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n log.debug(LOG_TAG, \"close with error: \" + error);\n this.stream = null;\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 this.close(PersistentStreamState.Error, error);\n };\n return PersistentStream;\n}());\nexport { PersistentStream };\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the openHandler, any number of listen and\n * unlisten calls calls can be sent to control what changes will be sent from\n * the server for ListenResponses.\n */\nvar PersistentListenStream = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentListenStream, _super);\n function PersistentListenStream(queue, connection, credentials, serializer) {\n var _this = _super.call(this, queue, TimerId.ListenStreamConnectionBackoff, TimerId.ListenStreamIdle, connection, credentials) || this;\n _this.serializer = serializer;\n return _this;\n }\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\n * Registers interest in the results of the given query. If the query\n * includes a resumeToken it will be included in the request. Results that\n * affect the query will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n if (labels) {\n request.labels = labels;\n }\n this.sendRequest(request);\n };\n /**\n * Unregisters interest in the results of the query associated with the\n * given targetId.\n */\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n };\n return PersistentListenStream;\n}(PersistentStream));\nexport { PersistentListenStream };\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 */\nvar PersistentWriteStream = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentWriteStream, _super);\n function PersistentWriteStream(queue, connection, credentials, serializer) {\n var _this = _super.call(this, queue, TimerId.WriteStreamConnectionBackoff, TimerId.WriteStreamIdle, connection, credentials) || this;\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get: function () {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n });\n // Override of PersistentStream.start\n PersistentWriteStream.prototype.start = function (listener) {\n this.handshakeComplete_ = false;\n _super.prototype.start.call(this, listener);\n };\n PersistentWriteStream.prototype.tearDown = function () {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n };\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\n this.handshakeComplete_ = true;\n return this.listener.onHandshakeComplete();\n }\n else {\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.backoff.reset();\n var results = this.serializer.fromWriteResults(responseProto.writeResults);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\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 */\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\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 var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) { return _this.serializer.toMutation(mutation); })\n };\n this.sendRequest(request);\n };\n return PersistentWriteStream;\n}(PersistentStream));\nexport { PersistentWriteStream };\n\n//# sourceMappingURL=persistent_stream.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/persistent_stream.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as log from '../util/log';\nvar LOG_TAG = 'ExponentialBackoff';\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 */\nvar ExponentialBackoff = /** @class */ (function () {\n function ExponentialBackoff(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n queue, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n timerId, \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 initialDelayMs, \n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n backoffFactor, \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 */\n maxDelayMs) {\n this.queue = queue;\n this.timerId = timerId;\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n this.timerPromise = null;\n 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 */\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\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 */\n ExponentialBackoff.prototype.backoffAndRun = function (op) {\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 var delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();\n if (this.currentBaseMs > 0) {\n log.debug(LOG_TAG, \"Backing off for \" + delayWithJitterMs + \" ms \" +\n (\"(base delay: \" + this.currentBaseMs + \" ms)\"));\n }\n this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, delayWithJitterMs, op);\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n };\n ExponentialBackoff.prototype.cancel = function () {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n return ExponentialBackoff;\n}());\nexport { ExponentialBackoff };\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { maybeDocumentMap } from '../model/collections';\nimport { assert } from '../util/assert';\nimport { PersistentListenStream, PersistentWriteStream } from './persistent_stream';\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nvar Datastore = /** @class */ (function () {\n function Datastore(queue, connection, credentials, serializer) {\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n }\n Datastore.prototype.newPersistentWriteStream = function () {\n return new PersistentWriteStream(this.queue, this.connection, this.credentials, this.serializer);\n };\n Datastore.prototype.newPersistentWatchStream = function () {\n return new PersistentListenStream(this.queue, this.connection, this.credentials, this.serializer);\n };\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(function (m) { return _this.serializer.toMutation(m); })\n };\n return this.invokeRPC('Commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults);\n });\n };\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n var params = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(function (k) { return _this.serializer.toName(k); })\n };\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeRPC(rpcName, request, token);\n });\n };\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\n var _this = this;\n // TODO(mikelehen): Retry (with backoff) on token failures?\n return this.credentials.getToken(/*forceRefresh=*/ false).then(function (token) {\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\n });\n };\n return Datastore;\n}());\nexport { Datastore };\n\n//# sourceMappingURL=datastore.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/datastore.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { SnapshotVersion } from './snapshot_version';\nimport { documentVersionMap } from '../model/collections';\nimport { NoDocument } from '../model/document';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport { Code, FirestoreError } from '../util/error';\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nvar Transaction = /** @class */ (function () {\n function Transaction(datastore) {\n this.datastore = datastore;\n // The version of each document that was read during this transaction.\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion = doc.version;\n if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n }\n var existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n }\n else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) { return _this.recordVersion(doc); });\n return docs;\n });\n };\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n this.mutations = this.mutations.concat(mutations);\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 */\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n if (version) {\n return Precondition.updateTime(version);\n }\n else {\n return Precondition.NONE;\n }\n };\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n if (version && version.isEqual(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n }\n else if (version) {\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n }\n else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n };\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n Transaction.prototype.delete = function (key) {\n this.write([new DeleteMutation(key, this.precondition(key))]);\n // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\n };\n Transaction.prototype.commit = function () {\n var _this = this;\n var unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n return Transaction;\n}());\nexport { Transaction };\n\n//# sourceMappingURL=transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/transaction.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2018 Google Inc.\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 */\nimport { OnlineState } from '../core/types';\nimport * as log from '../util/log';\nimport { assert } from '../util/assert';\nimport { TimerId } from '../util/async_queue';\nvar LOG_TAG = 'OnlineStateTracker';\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\nvar MAX_WATCH_STREAM_FAILURES = 2;\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nvar ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\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 */\nvar OnlineStateTracker = /** @class */ (function () {\n function OnlineStateTracker(asyncQueue, onlineStateHandler) {\n this.asyncQueue = asyncQueue;\n this.onlineStateHandler = onlineStateHandler;\n /** The current OnlineState. */\n this.state = 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.watchStreamFailures = 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.onlineStateTimer = 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.shouldWarnClientIsOffline = true;\n }\n /**\n * Called by RemoteStore when a watch stream is started.\n *\n * It sets the OnlineState to Unknown and starts the onlineStateTimer\n * if necessary.\n */\n OnlineStateTracker.prototype.handleWatchStreamStart = function () {\n var _this = this;\n this.setAndBroadcast(OnlineState.Unknown);\n if (this.onlineStateTimer === null) {\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout, ONLINE_STATE_TIMEOUT_MS, function () {\n _this.onlineStateTimer = null;\n assert(_this.state === OnlineState.Unknown, 'Timer should be canceled if we transitioned to a different state.');\n log.debug(LOG_TAG, \"Watch stream didn't reach online or offline within \" +\n (ONLINE_STATE_TIMEOUT_MS + \"ms. Considering client offline.\"));\n _this.logClientOfflineWarningIfNecessary();\n _this.setAndBroadcast(OnlineState.Offline);\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n return Promise.resolve();\n });\n }\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 */\n OnlineStateTracker.prototype.handleWatchStreamFailure = function () {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n }\n else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n this.logClientOfflineWarningIfNecessary();\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\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 */\n OnlineStateTracker.prototype.set = function (newState) {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n this.setAndBroadcast(newState);\n };\n OnlineStateTracker.prototype.setAndBroadcast = function (newState) {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n };\n OnlineStateTracker.prototype.logClientOfflineWarningIfNecessary = function () {\n if (this.shouldWarnClientIsOffline) {\n log.error('Could not reach Firestore backend.');\n this.shouldWarnClientIsOffline = false;\n }\n };\n OnlineStateTracker.prototype.clearOnlineStateTimer = function () {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n };\n return OnlineStateTracker;\n}());\nexport { OnlineStateTracker };\n\n//# sourceMappingURL=online_state_tracker.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/online_state_tracker.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Transaction } from '../core/transaction';\nimport { OnlineState } from '../core/types';\nimport { QueryData, QueryPurpose } from '../local/query_data';\nimport { NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { BATCHID_UNKNOWN, MutationBatchResult } from '../model/mutation_batch';\nimport { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { ResetMapping, UpdateMapping } from './remote_event';\nimport { isPermanentError } from './rpc_error';\nimport { WatchChangeAggregator, WatchTargetChange, WatchTargetChangeState } from './watch_change';\nimport { OnlineStateTracker } from './online_state_tracker';\nvar LOG_TAG = 'RemoteStore';\n// TODO(b/35853402): Negotiate this with the stream.\nvar MAX_PENDING_WRITES = 10;\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nvar RemoteStore = /** @class */ (function () {\n function RemoteStore(\n /**\n * The local store, used to fill the write pipeline with outbound\n * mutations and resolve existence filter mismatches.\n */\n localStore, \n /** The client-side proxy for interacting with the backend. */\n datastore, asyncQueue, onlineStateHandler) {\n this.localStore = localStore;\n this.datastore = datastore;\n this.pendingWrites = [];\n this.lastBatchSeen = BATCHID_UNKNOWN;\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.listenTargets = {};\n /**\n * A mapping of targetId to pending acks needed.\n *\n * If a targetId is present in this map, then we're waiting for watch to\n * acknowledge a removal or addition of the target. If a target is not in this\n * mapping, and it's in the listenTargets map, then we consider the target to\n * be active.\n *\n * We increment the count here every time we issue a request over the stream\n * to watch or unwatch. We then decrement the count every time we get a target\n * added or target removed message from the server. Once the count is equal to\n * 0 we know that the client and server are in the same state (once this state\n * is reached the targetId is removed from the map to free the memory).\n */\n this.pendingTargetResponses = {};\n this.accumulatedWatchChanges = [];\n this.watchStream = null;\n this.writeStream = null;\n this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler);\n }\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n RemoteStore.prototype.isNetworkEnabled = function () {\n assert((this.watchStream == null) === (this.writeStream == null), 'WatchStream and WriteStream should both be null or non-null');\n return this.watchStream != null;\n };\n /** Re-enables the network. Idempotent. */\n RemoteStore.prototype.enableNetwork = function () {\n var _this = this;\n if (this.isNetworkEnabled()) {\n return Promise.resolve();\n }\n // Create new streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream();\n this.writeStream = this.datastore.newPersistentWriteStream();\n // Load any saved stream token from persistent storage\n return this.localStore.getLastStreamToken().then(function (token) {\n _this.writeStream.lastStreamToken = token;\n if (_this.shouldStartWatchStream()) {\n _this.startWatchStream();\n }\n else {\n _this.onlineStateTracker.set(OnlineState.Unknown);\n }\n return _this.fillWritePipeline(); // This may start the writeStream.\n });\n };\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n RemoteStore.prototype.disableNetwork = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.disableNetworkInternal();\n // Set the OnlineState to Offline so get()s return from cache, etc.\n this.onlineStateTracker.set(OnlineState.Offline);\n return [2 /*return*/];\n });\n });\n };\n /**\n * Disables the network, if it is currently enabled.\n */\n RemoteStore.prototype.disableNetworkInternal = function () {\n if (this.isNetworkEnabled()) {\n // NOTE: We're guaranteed not to get any further events from these streams (not even a close\n // event).\n this.watchStream.stop();\n this.writeStream.stop();\n this.cleanUpWatchStreamState();\n this.cleanUpWriteStreamState();\n this.writeStream = null;\n this.watchStream = null;\n }\n };\n RemoteStore.prototype.shutdown = function () {\n log.debug(LOG_TAG, 'RemoteStore shutting down.');\n this.disableNetworkInternal();\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.onlineStateTracker.set(OnlineState.Unknown);\n return Promise.resolve();\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n RemoteStore.prototype.listen = function (queryData) {\n assert(!objUtils.contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!');\n // Mark this as something the client is currently listening for.\n this.listenTargets[queryData.targetId] = queryData;\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n }\n else if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(objUtils.contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n delete this.listenTargets[targetId];\n if (this.isNetworkEnabled() && this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n if (objUtils.isEmpty(this.listenTargets)) {\n this.watchStream.markIdle();\n }\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 */\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\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 */\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n /**\n * Increment the mapping of how many acks are needed from watch before we can\n * consider the server to be 'in-sync' with the client's active targets.\n */\n RemoteStore.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n this.pendingTargetResponses[targetId] =\n (this.pendingTargetResponses[targetId] || 0) + 1;\n };\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWriteStream() called when shouldStartWatchStream() is false.');\n this.watchStream.start({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n this.onlineStateTracker.handleWatchStreamStart();\n };\n /**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return (this.isNetworkEnabled() &&\n !this.watchStream.isStarted() &&\n !objUtils.isEmpty(this.listenTargets));\n };\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n // If the connection is closed then we'll never get a snapshot version for\n // the accumulated changes and so we'll never be able to complete the batch.\n // When we start up again the server is going to resend these changes\n // anyway, so just toss the accumulated state.\n this.accumulatedWatchChanges = [];\n this.pendingTargetResponses = {};\n };\n RemoteStore.prototype.onWatchStreamOpen = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib_1.__generator(this, function (_a) {\n // TODO(b/35852690): close the stream again (with some timeout?) if no watch\n // targets are active\n objUtils.forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWatchStreamClose = function (error) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n assert(this.isNetworkEnabled(), 'onWatchStreamClose() should only be called when the network is enabled');\n this.cleanUpWatchStreamState();\n this.onlineStateTracker.handleWatchStreamFailure();\n // If there was an error, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.startWatchStream();\n }\n else {\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var changes;\n return tslib_1.__generator(this, function (_a) {\n // Mark the client as online since we got a message from the server\n this.onlineStateTracker.set(OnlineState.Online);\n if (watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return [2 /*return*/, this.handleTargetError(watchChange)];\n }\n // Accumulate watch changes but don't process them if there's no\n // snapshotVersion or it's older than a previous snapshot we've processed\n // (can happen after we resume a target using a resume token).\n this.accumulatedWatchChanges.push(watchChange);\n if (!snapshotVersion.isEqual(SnapshotVersion.MIN) &&\n snapshotVersion.compareTo(this.localStore.getLastRemoteSnapshotVersion()) >= 0) {\n changes = this.accumulatedWatchChanges;\n this.accumulatedWatchChanges = [];\n return [2 /*return*/, this.handleWatchChangeBatch(snapshotVersion, changes)];\n }\n return [2 /*return*/];\n });\n });\n };\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 RemoteStore.prototype.handleWatchChangeBatch = function (snapshotVersion, changes) {\n var _this = this;\n var aggregator = new WatchChangeAggregator(snapshotVersion, this.listenTargets, this.pendingTargetResponses);\n aggregator.addChanges(changes);\n var remoteEvent = aggregator.createRemoteEvent();\n // Get the new response counts from the aggregator\n this.pendingTargetResponses = aggregator.pendingTargetResponses;\n var promises = [];\n // Handle existence filters and existence filter mismatches.\n objUtils.forEachNumber(aggregator.existenceFilters, function (targetId, filter) {\n var queryData = _this.listenTargets[targetId];\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n }\n var query = queryData.query;\n if (query.isDocumentQuery()) {\n if (filter.count === 0) {\n // The existence filter told us the document does not exist.\n // We need to deduce that this document does not exist and apply\n // a deleted document to our updates. Without applying a deleted\n // document there might be another query that will raise this\n // document as part of a snapshot until it is resolved,\n // essentially exposing inconsistency between queries.\n var key = new DocumentKey(query.path);\n var deletedDoc = new NoDocument(key, snapshotVersion);\n remoteEvent.addDocumentUpdate(deletedDoc);\n }\n else {\n assert(filter.count === 1, 'Single document existence filter with count: ' + filter.count);\n }\n }\n else {\n // Not a document query.\n var promise = _this.localStore\n .remoteDocumentKeys(targetId)\n .then(function (trackedRemote) {\n if (remoteEvent.targetChanges[targetId]) {\n var mapping = remoteEvent.targetChanges[targetId].mapping;\n if (mapping !== null) {\n if (mapping instanceof UpdateMapping) {\n trackedRemote = mapping.applyToKeySet(trackedRemote);\n }\n else {\n assert(mapping instanceof ResetMapping, 'Expected either reset or update mapping but got something else: ' +\n mapping);\n trackedRemote = mapping.documents;\n }\n }\n }\n if (trackedRemote.size !== filter.count) {\n // Existence filter mismatch, resetting mapping.\n // Make sure the mismatch is exposed in the remote event.\n remoteEvent.handleExistenceFilterMismatch(targetId);\n // Clear the resume token for the query, since we're in a\n // known mismatch state.\n var newQueryData = new QueryData(query, targetId, queryData.purpose);\n _this.listenTargets[targetId] = newQueryData;\n // Cause a hard reset by unwatching and rewatching\n // immediately, but deliberately don't send a resume token\n // so that we get a full update.\n // Make sure we expect that this acks are going to happen.\n _this.sendUnwatchRequest(targetId);\n // Mark the query we send as being on behalf of an existence\n // filter mismatch, but don't actually retain that in\n // listenTargets. This ensures that we flag the first\n // re-listen this way without impacting future listens of\n // this target (that might happen e.g. on reconnect).\n var requestQueryData = new QueryData(query, targetId, QueryPurpose.ExistenceFilterMismatch);\n _this.sendWatchRequest(requestQueryData);\n }\n });\n promises.push(promise);\n }\n });\n return Promise.all(promises).then(function () {\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n objUtils.forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (queryData) {\n _this.listenTargets[targetId] = queryData.update({\n resumeToken: change.resumeToken,\n snapshotVersion: change.snapshotVersion\n });\n }\n }\n });\n // Finally handle remote event\n return _this.syncEngine.applyRemoteEvent(remoteEvent);\n });\n };\n /** Handles an error on a target */\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // A watched target might have been removed already.\n if (objUtils.contains(this.listenTargets, targetId)) {\n delete this.listenTargets[targetId];\n return [2 /*return*/, this.syncEngine.rejectListen(targetId, error)];\n }\n return [2 /*return*/];\n });\n }); });\n });\n return promiseChain;\n };\n RemoteStore.prototype.cleanUpWriteStreamState = function () {\n this.lastBatchSeen = BATCHID_UNKNOWN;\n log.debug(LOG_TAG, 'Stopping write stream with ' +\n this.pendingWrites.length +\n ' pending writes');\n this.pendingWrites = [];\n };\n /**\n * Notifies that there are new mutations to process in the queue. This is\n * typically called by SyncEngine after it has sent mutations to LocalStore.\n */\n RemoteStore.prototype.fillWritePipeline = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib_1.__generator(this, function (_a) {\n if (this.canWriteMutations()) {\n return [2 /*return*/, this.localStore\n .nextMutationBatch(this.lastBatchSeen)\n .then(function (batch) {\n if (batch === null) {\n if (_this.pendingWrites.length === 0) {\n _this.writeStream.markIdle();\n }\n }\n else {\n _this.commit(batch);\n return _this.fillWritePipeline();\n }\n })];\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Returns true if the backend can accept additional write requests.\n *\n * When sending mutations to the write stream (e.g. in fillWritePipeline),\n * call this method first to check if more mutations can be sent.\n *\n * Currently the only thing that can prevent the backend from accepting\n * write requests is if there are too many requests already outstanding. As\n * writes complete the backend will be able to accept more.\n */\n RemoteStore.prototype.canWriteMutations = function () {\n return (this.isNetworkEnabled() && this.pendingWrites.length < MAX_PENDING_WRITES);\n };\n // For testing\n RemoteStore.prototype.outstandingWrites = function () {\n return this.pendingWrites.length;\n };\n /**\n * Given mutations to commit, actually commits them to the Datastore. Note\n * that this does *not* return a Promise specifically because the AsyncQueue\n * should not block operations for this.\n */\n RemoteStore.prototype.commit = function (batch) {\n assert(this.canWriteMutations(), \"commit called when batches can't be written\");\n this.lastBatchSeen = batch.batchId;\n this.pendingWrites.push(batch);\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n else if (this.isNetworkEnabled() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return (this.isNetworkEnabled() &&\n !this.writeStream.isStarted() &&\n this.pendingWrites.length > 0);\n };\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n };\n RemoteStore.prototype.onWriteStreamOpen = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.writeStream.writeHandshake();\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this;\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(function () {\n // Drain any pending writes.\n //\n // Note that at this point pendingWrites contains mutations that\n // have already been accepted by fillWritePipeline/commitBatch. If\n // the pipeline is full, canWriteMutations will be false, despite\n // the fact that we actually need to send mutations over.\n //\n // This also means that this method indirectly respects the limits\n // imposed by canWriteMutations since writes can't be added to the\n // pendingWrites array when canWriteMutations is false. If the\n // limits imposed by canWriteMutations actually protect us from\n // DOSing ourselves then those limits won't be exceeded here and\n // we'll continue to make progress.\n for (var _i = 0, _a = _this.pendingWrites; _i < _a.length; _i++) {\n var batch = _a[_i];\n _this.writeStream.writeMutations(batch.mutations);\n }\n });\n };\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this;\n // This is a response to a write containing mutations and should be\n // correlated to the first pending write.\n assert(this.pendingWrites.length > 0, 'Got result for empty pending writes');\n var batch = this.pendingWrites.shift();\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n RemoteStore.prototype.onWriteStreamClose = function (error) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n var errorHandling;\n return tslib_1.__generator(this, function (_a) {\n assert(this.isNetworkEnabled(), 'onWriteStreamClose() should only be called when the network is enabled');\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.pendingWrites.length > 0) {\n assert(!!error, 'We have pending writes, but the write stream closed without an error');\n errorHandling = void 0;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error);\n }\n else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error);\n }\n return [2 /*return*/, errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n })];\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.handleHandshakeError = function (error) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error.code) || error.code === Code.ABORTED) {\n log.debug(LOG_TAG, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return [2 /*return*/, this.localStore.setLastStreamToken(emptyByteString())];\n }\n else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.handleWriteError = function (error) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n var batch;\n return tslib_1.__generator(this, function (_a) {\n if (isPermanentError(error.code)) {\n batch = this.pendingWrites.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 this.writeStream.inhibitBackoff();\n return [2 /*return*/, this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n })];\n }\n else {\n // Transient error, just let the retry logic kick in.\n }\n return [2 /*return*/];\n });\n });\n };\n RemoteStore.prototype.createTransaction = function () {\n return new Transaction(this.datastore);\n };\n RemoteStore.prototype.handleUserChange = function (user) {\n log.debug(LOG_TAG, 'RemoteStore changing users: uid=', user.uid);\n // If the network has been explicitly disabled, make sure we don't\n // accidentally re-enable it.\n if (this.isNetworkEnabled()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n return this.enableNetwork();\n }\n };\n return RemoteStore;\n}());\nexport { RemoteStore };\n\n//# sourceMappingURL=remote_store.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/remote/remote_store.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { EventManager, QueryListener } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport { EagerGarbageCollector } from '../local/eager_garbage_collector';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistence } from '../local/memory_persistence';\nimport { NoOpGarbageCollector } from '../local/no_op_garbage_collector';\nimport { Datastore } from '../remote/datastore';\nimport { RemoteStore } from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code } from '../util/error';\nimport { debug } from '../util/log';\nimport { Deferred } from '../util/promise';\nvar LOG_TAG = 'FirestoreClient';\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 */\nvar FirestoreClient = /** @class */ (function () {\n function FirestoreClient(platform, databaseInfo, credentials, \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 asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n }\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param usePersistence Whether or not to attempt to enable persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n FirestoreClient.prototype.start = function (usePersistence) {\n var _this = this;\n // We defer our initialization until we get the current user from\n // setUserChangeListener(). We block the async queue until we got the\n // initial user and the initialization is completed. This will prevent\n // any scheduled work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n var initializationDone = new Deferred();\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n var persistenceResult = new Deferred();\n var initialized = false;\n this.credentials.setUserChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n _this.initializePersistence(usePersistence, persistenceResult)\n .then(function () { return _this.initializeRest(user); })\n .then(initializationDone.resolve, initializationDone.reject);\n }\n else {\n _this.asyncQueue.enqueue(function () {\n return _this.handleUserChange(user);\n });\n }\n });\n // Block the async queue until initialization is done\n this.asyncQueue.enqueue(function () {\n return initializationDone.promise;\n });\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n return this.asyncQueue.enqueue(function () {\n return _this.remoteStore.enableNetwork();\n });\n };\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param usePersistence indicates whether or not to use offline persistence\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n FirestoreClient.prototype.initializePersistence = function (usePersistence, persistenceResult) {\n var _this = this;\n if (usePersistence) {\n return this.startIndexedDbPersistence()\n .then(persistenceResult.resolve)\n .catch(function (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n // An unknown failure on the first stage shuts everything down.\n if (!_this.canFallback(error)) {\n return Promise.reject(error);\n }\n console.warn('Error enabling offline storage. Falling back to' +\n ' storage disabled: ' +\n error);\n return _this.startMemoryPersistence();\n });\n }\n else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n FirestoreClient.prototype.canFallback = function (error) {\n return (error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED);\n };\n /**\n * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n FirestoreClient.prototype.startIndexedDbPersistence = function () {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n this.garbageCollector = new NoOpGarbageCollector();\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo);\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n this.persistence = new IndexedDbPersistence(storagePrefix, serializer);\n return this.persistence.start();\n };\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.garbageCollector = new EagerGarbageCollector();\n this.persistence = new MemoryPersistence();\n return this.persistence.start();\n };\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n FirestoreClient.prototype.initializeRest = function (user) {\n var _this = this;\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(function (connection) {\n _this.localStore = new LocalStore(_this.persistence, user, _this.garbageCollector);\n var serializer = _this.platform.newSerializer(_this.databaseInfo.databaseId);\n var datastore = new Datastore(_this.asyncQueue, connection, _this.credentials, serializer);\n var onlineStateChangedHandler = function (onlineState) {\n _this.syncEngine.applyOnlineStateChange(onlineState);\n _this.eventMgr.applyOnlineStateChange(onlineState);\n };\n _this.remoteStore = new RemoteStore(_this.localStore, datastore, _this.asyncQueue, onlineStateChangedHandler);\n _this.syncEngine = new SyncEngine(_this.localStore, _this.remoteStore, user);\n // Setup wiring between sync engine and remote store\n _this.remoteStore.syncEngine = _this.syncEngine;\n _this.eventMgr = new EventManager(_this.syncEngine);\n // NOTE: RemoteStore depends on LocalStore (for persisting stream\n // tokens, refilling mutation queue, etc.) so must be started after\n // LocalStore.\n return _this.localStore.start();\n })\n .then(function () {\n return _this.remoteStore.start();\n });\n };\n FirestoreClient.prototype.handleUserChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(LOG_TAG, 'User Changed: ' + user.uid);\n return this.syncEngine.handleUserChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n return this.asyncQueue.enqueue(function () {\n return _this.remoteStore.disableNetwork();\n });\n };\n FirestoreClient.prototype.shutdown = function () {\n var _this = this;\n return this.asyncQueue\n .enqueue(function () {\n _this.credentials.removeUserChangeListener();\n return _this.remoteStore.shutdown();\n })\n .then(function () {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n return _this.persistence.shutdown();\n });\n };\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n var listener = new QueryListener(query, observer, options);\n this.asyncQueue.enqueue(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n this.asyncQueue.enqueue(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n var deferred = new Deferred();\n this.asyncQueue.enqueue(function () { return _this.syncEngine.write(mutations, deferred); });\n return deferred.promise;\n };\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this;\n // We have to wait for the async queue to be sure syncEngine is initialized.\n return this.asyncQueue\n .enqueue(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) {\n return [2 /*return*/];\n }); }); })\n .then(function () { return _this.syncEngine.runTransaction(updateFunction); });\n };\n return FirestoreClient;\n}());\nexport { FirestoreClient };\n\n//# sourceMappingURL=firestore_client.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/core/firestore_client.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 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 */\nvar AsyncObserver = /** @class */ (function () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = false;\n }\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n return AsyncObserver;\n}());\nexport { AsyncObserver };\n\n//# sourceMappingURL=async_observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/util/async_observer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar User = /** @class */ (function () {\n function User(uid) {\n this.uid = uid;\n }\n User.prototype.isAuthenticated = function () {\n return this.uid != null;\n };\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n User.prototype.toKey = function () {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n }\n else {\n return 'anonymous-user';\n }\n };\n User.prototype.isEqual = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n User.UNAUTHENTICATED = new User(null);\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}());\nexport { User };\n\n//# sourceMappingURL=user.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/auth/user.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { makeConstructorPrivate } from '../util/api';\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\nvar FieldValueImpl = /** @class */ (function () {\n function FieldValueImpl() {\n }\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n FieldValueImpl.prototype.isEqual = function (other) {\n return this === other;\n };\n return FieldValueImpl;\n}());\nexport { FieldValueImpl };\nvar DeleteFieldValueImpl = /** @class */ (function (_super) {\n tslib_1.__extends(DeleteFieldValueImpl, _super);\n function DeleteFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl));\nexport { DeleteFieldValueImpl };\nvar ServerTimestampFieldValueImpl = /** @class */ (function (_super) {\n tslib_1.__extends(ServerTimestampFieldValueImpl, _super);\n function ServerTimestampFieldValueImpl() {\n return _super.call(this) || this;\n }\n /** Singleton instance. */\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl));\nexport { ServerTimestampFieldValueImpl };\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\nexport var PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n\n//# sourceMappingURL=field_value.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../firestore/dist/esm/src/api/field_value.js\n// module id = null\n// module chunks = ","(function() {var g,goog=goog||{},k=this;function l(a){return\"string\"==typeof a}function aa(){}\nfunction ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";return b}function n(a){return\"array\"==ba(a)}function ca(a){var b=ba(a);return\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function da(a){return\"function\"==ba(a)}function ea(a){var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var p=\"closure_uid_\"+(1E9*Math.random()>>>0),fa=0;function ha(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ia(a,b,c){if(!a)throw Error();if(2b?null:l(a)?a.charAt(b):a[b]}function ua(a){if(!n(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0}function va(a){return Array.prototype.concat.apply([],arguments)}function wa(a){var b=a.length;if(0b?1:0};var w;a:{var Aa=k.navigator;if(Aa){var Ba=Aa.userAgent;if(Ba){w=Ba;break a}}w=\"\"}function x(a){return-1!=w.indexOf(a)};function Ca(a,b,c){for(var d in a)b.call(c,a[d],d,a)}function Da(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Ea(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b}function Fa(a){var b={},c;for(c in a)b[c]=a[c];return b}var Ga=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");\nfunction Ha(a,b){for(var c,d,e=1;eparseFloat(Sa)){Ra=String(Ua);break a}}Ra=Sa}var Ka={};\nfunction Va(a){return Ja(a,function(){for(var b=0,c=ya(String(Ra)).split(\".\"),d=ya(String(a)).split(\".\"),e=Math.max(c.length,d.length),f=0;0==b&&f=a.keyCode)a.keyCode=-1}catch(b){}};var db=\"closure_listenable_\"+(1E6*Math.random()|0),eb=0;function fb(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ga=e;this.key=++eb;this.Z=this.ba=!1}function gb(a){a.Z=!0;a.listener=null;a.proxy=null;a.src=null;a.ga=null};function hb(a){this.src=a;this.a={};this.b=0}hb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var h=ib(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(h){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=xb(d[e],a,!0,b);c=c&&f}for(e=0;e>>0);function pb(a){if(da(a))return a;a[zb]||(a[zb]=function(b){return a.handleEvent(b)});return a[zb]};function A(){u.call(this);this.f=new hb(this);this.N=this;this.J=null}t(A,u);A.prototype[db]=!0;g=A.prototype;g.addEventListener=function(a,b,c,d){nb(this,a,b,c,d)};g.removeEventListener=function(a,b,c,d){vb(this,a,b,c,d)};\ng.dispatchEvent=function(a){var b,c=this.J;if(c)for(b=[];c;c=c.J)b.push(c);c=this.N;var d=a.type||a;if(l(a))a=new z(a,c);else if(a instanceof z)a.target=a.target||c;else{var e=a;a=new z(d,c);Ha(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var h=a.a=b[f];e=Ab(h,d,!0,a)&&e}h=a.a=c;e=Ab(h,d,!0,a)&&e;e=Ab(h,d,!1,a)&&e;if(b)for(f=0;fb.b&&(b.b++,a.next=b.a,b.a=a)}Wb=!1};function Xb(a,b){A.call(this);this.b=a||1;this.a=b||k;this.c=q(this.lb,this);this.g=r()}t(Xb,A);g=Xb.prototype;g.ea=!1;g.O=null;g.lb=function(){if(this.ea){var a=r()-this.g;0=nc(this).value)for(da(b)&&(b=b()),a=new fc(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};\nvar oc={},pc=null;function qc(a){pc||(pc=new hc(\"\"),oc[\"\"]=pc,pc.c=lc);var b;if(!(b=oc[a])){b=new hc(a);var c=a.lastIndexOf(\".\"),d=a.substr(c+1);c=qc(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;oc[a]=b}return b};function C(a,b){a&&a.log(jc,b,void 0)}function rc(a,b){a&&a.log(kc,b,void 0)}function D(a,b){a&&a.log(mc,b,void 0)};function sc(){this.a=qc(\"goog.labs.net.webChannel.WebChannelDebug\");this.b=!0}sc.prototype.Ea=function(){this.b=!1};function tc(a,b,c,d,e,f){E(a,function(){if(a.b)if(f){var h=\"\";for(var m=f.split(\"&\"),v=0;ve.length)){var f=e[1];if(n(f)&&!(1>f.length)){var h=f[0];if(\"noop\"!=h&&\"stop\"!=h&&\"close\"!=h)for(var m=1;mb||3==b&&!Na&&!a.a.V())){a.B||4!=b||7==c||(8==c||0>=d?zc(3):zc(2));ad(a);var e=a.a.W();a.C=e;(c=a.a.V())||G(a.b,function(){return\"No response text for uri \"+a.g+\" status \"+e});a.f=200==e;uc(a.b,a.o,a.g,a.c,a.T,b,e);if(a.f){if(d=bd(a))F(a.b,a.c,d,\"Initial handshake response via X-HTTP-Initial-Response\"),a.v=!0,cd(a,d);a.K?(dd(a,b,c),Na&&a.f&&3==b&&ed(a)):(F(a.b,a.c,c,null),cd(a,c));4==b&&fd(a);a.f&&!a.B&&(4==b?a.i.ta(a):(a.f=!1,Yc(a)))}else 400==\ne&&0b.length)return Tc;b=b.substr(d,c);a.G=d+c;return b}g.cancel=function(){this.B=!0;fd(this)};function Yc(a){a.U=r()+a.R;jd(a,a.R)}function jd(a,b){if(null!=a.s)throw Error(\"WatchDog timer not null\");a.s=Dc(q(a.gb,a),b)}function ad(a){a.s&&(k.clearTimeout(a.s),a.s=null)}\ng.gb=function(){this.s=null;var a=r();0<=a-this.U?(this.f&&H(this.b,\"Received watchdog timeout even though request loaded successfully\"),wc(this.b,this.g),2!=this.J&&(zc(3),K(17)),fd(this),this.m=2,gd(this)):(C(this.b.a,\"WatchDog timer called too early\"),jd(this,this.U-a))};function gd(a){a.i.Ka()||a.B||a.i.ta(a)}function fd(a){ad(a);var b=a.I;b&&\"function\"==typeof b.$&&b.$();a.I=null;Yb(a.S);ec(a.L);a.a&&(b=a.a,a.a=null,b.abort(),b.$())}\nfunction cd(a,b){try{a.i.Na(a,b),zc(4)}catch(c){xc(a.b,c,\"Error in httprequest callback\")}};function kd(a){if(a.A&&\"function\"==typeof a.A)return a.A();if(l(a))return a.split(\"\");if(ca(a)){for(var b=[],c=a.length,d=0;d2*a.c&&md(a),!0):!1}function md(a){if(a.c!=a.a.length){for(var b=0,c=0;bb)throw Error(\"Bad port number \"+b);a.i=b}else a.i=null}function ud(a,b,c){b instanceof xd?(a.c=b,Dd(a.c,a.h)):(c||(b=yd(b,Ed)),a.c=new xd(b,a.h))}\nfunction R(a,b,c){a.c.set(b,c)}function Zc(a,b,c){n(c)||(c=[String(c)]);Fd(a.c,b,c)}function Vc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^r()).toString(36));return a}function Gd(a){return a instanceof Q?M(a):new Q(a,void 0)}function Hd(a,b,c,d){var e=new Q(null,void 0);a&&rd(e,a);b&&sd(e,b);c&&td(e,c);d&&(e.a=d);return e}function wd(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}\nfunction yd(a,b,c){return l(a)?(a=encodeURI(a).replace(b,Id),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Id(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var zd=/[#\\/\\?@]/g,Bd=/[#\\?:]/g,Ad=/[#\\?]/g,Ed=/[#\\?@]/g,Cd=/#/g;function xd(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function S(a){a.a||(a.a=new O,a.b=0,a.c&&qd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}g=xd.prototype;\ng.add=function(a,b){S(this);this.c=null;a=Jd(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function Kd(a,b){S(a);b=Jd(a,b);P(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,od(a.a,b))}function Ld(a,b){S(a);b=Jd(a,b);return P(a.a.b,b)}g.forEach=function(a,b){S(this);this.a.forEach(function(c,d){ra(c,function(c){a.call(b,c,d,this)},this)},this)};\ng.M=function(){S(this);for(var a=this.a.A(),b=this.a.M(),c=[],d=0;d=a.f:!1}function de(a,b){a.b?a=a.b==b:a.a?(b=Xd(b),a=P(a.a.a.b,b)):a=!1;return a}function be(a,b){a.a?a.a.add(b):a.b=b}\nfunction ee(a,b){if(a.b&&a.b==b)a.b=null;else{var c;if(c=a.a)c=Xd(b),c=P(a.a.a.b,c);c&&od(a.a.a,Xd(b))}}Zd.prototype.cancel=function(){this.c=fe(this);this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ra(this.a.A(),function(a){a.cancel()}),nd(this.a.a))};function fe(a){if(null!=a.b)return a.c.concat(a.b.u);if(null!=a.a&&0!=a.a.a.c){var b=a.c;ra(a.a.A(),function(a){b=b.concat(a.u)});return b}return wa(a.c)}function ge(a,b){a.c=a.c.concat(b)};function he(){}he.prototype.stringify=function(a){return k.JSON.stringify(a,void 0)};he.prototype.parse=function(a){return k.JSON.parse(a,void 0)};function ie(){this.a=new he}function je(a,b,c){var d=c||\"\";try{ld(a,function(a,c){var e=a;ea(a)&&(e=Db(a));b.push(d+c+\"=\"+encodeURIComponent(e))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function ke(a,b){var c=new sc;G(c,\"TestLoadImage: loading \"+a);var d=new Image;d.onload=ja(le,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ja(le,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ja(le,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ja(le,c,d,\"TestLoadImage: timeout\",!1,b);k.setTimeout(function(){if(d.ontimeout)d.ontimeout()},1E4);d.src=a}function le(a,b,c,d,e){try{G(a,c),b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d)}catch(f){xc(a,f)}};function T(a){A.call(this);this.headers=new O;this.D=a||null;this.c=!1;this.v=this.a=null;this.K=this.u=\"\";this.j=0;this.g=\"\";this.h=this.I=this.s=this.G=!1;this.l=0;this.B=null;this.L=me;this.C=this.o=!1}t(T,A);var me=\"\";T.prototype.b=qc(\"goog.net.XhrIo\");var ne=/^https?$/i,oe=[\"POST\",\"PUT\"];g=T.prototype;\ng.fa=function(a,b,c,d){if(this.a)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.u+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.u=a;this.g=\"\";this.j=0;this.K=b;this.G=!1;this.c=!0;this.a=this.D?Pc(this.D):Pc(Nc);this.v=this.D?Lc(this.D):Lc(Nc);this.a.onreadystatechange=q(this.Ma,this);try{D(this.b,U(this,\"Opening Xhr\")),this.I=!0,this.a.open(b,String(a),!0),this.I=!1}catch(f){D(this.b,U(this,\"Error opening Xhr: \"+f.message));pe(this,f);return}a=c||\"\";var e=new O(this.headers);\nd&&ld(d,function(a,b){e.set(b,a)});d=sa(e.M());c=k.FormData&&a instanceof k.FormData;!(0<=qa(oe,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(a,b){this.a.setRequestHeader(b,a)},this);this.L&&(this.a.responseType=this.L);\"withCredentials\"in this.a&&this.a.withCredentials!==this.o&&(this.a.withCredentials=this.o);try{qe(this),0c&&(c=a.length);d=a.indexOf(\"?\");if(0>d||d>c){d=c;var e=\"\"}else e=a.substring(d+1,c);a=[a.substr(0,d),e,a.substr(c)];c=a[1];a[1]=b?c?c+\"&\"+b:b:c;a=a[0]+(a[1]?\"?\"+a[1]:\"\")+a[2]}return a}R(a,b,c);return a};function xe(a){this.xa=0;this.g=[];this.a=new sc;this.I=new Vd;this.X=this.ua=this.D=this.ja=this.b=this.K=this.j=this.U=this.h=this.L=this.i=null;this.Va=this.R=0;this.Ua=a&&a.Eb||!1;this.ka=this.C=this.s=this.l=this.m=this.f=null;this.u=this.wa=this.N=-1;this.T=this.B=this.v=0;this.G=void 0;this.S=a&&a.supportsCrossDomainXhr||!1;this.J=\"\";this.c=new Zd(a&&a.concurrentRequestLimit);this.la=new ie;this.o=a&&void 0!==a.backgroundChannelTest?a.backgroundChannelTest:!0;(this.va=a&&a.fastHandshake||!1)&&\n!this.o&&(C(this.a.a,\"Force backgroundChannelTest when fastHandshake is enabled.\"),this.o=!0);a&&a.Ea&&this.a.Ea()}g=xe.prototype;g.na=8;g.F=1;\nfunction ye(a){G(a.a,\"disconnect()\");ze(a);if(3==a.F){var b=a.R++,c=M(a.D);R(c,\"SID\",a.J);R(c,\"RID\",b);R(c,\"TYPE\",\"terminate\");Ae(a,c);b=new L(a,a.a,b,void 0);b.J=2;b.h=Vc(M(c));c=!1;k.navigator&&k.navigator.sendBeacon&&(c=k.navigator.sendBeacon(b.h.toString(),\"\"));!c&&k.Image&&((new Image).src=b.h,c=!0);c||(b.a=b.i.ca(null),b.a.fa(b.h));b.D=r();Yc(b)}Be(a)}\nfunction ze(a){a.C&&(a.C.abort(),a.C=null);a.b&&(a.b.cancel(),a.b=null);a.l&&(k.clearTimeout(a.l),a.l=null);Ce(a);a.c.cancel();a.m&&(k.clearTimeout(a.m),a.m=null)}function De(a,b){1E3==a.g.length&&H(a.a,function(){return\"Already have 1000 queued maps upon queueing \"+Db(b)});a.g.push(new Yd(a.Va++,b));3==a.F&&Ee(a)}g.Ka=function(){return 0==this.F};function Ee(a){ce(a.c)||a.m||(a.m=Dc(q(a.Pa,a),0),a.v=0)}\nfunction Fe(a,b){var c=a.c;if((c.b?1:c.a?c.a.a.c:0)>=a.c.f-(a.m?1:0))return H(a.a,\"Unexpected retry request is scheduled.\"),!1;if(a.m)return G(a.a,\"Use the retry request that is already scheduled.\"),a.g=b.u.concat(a.g),!0;if(1==a.F||2==a.F||a.v>=(a.Ua?0:2))return!1;G(a.a,\"Going to retry POST\");a.m=Dc(q(a.Pa,a,b),Ge(a,a.v));a.v++;return!0}\ng.Pa=function(a){this.m=null;G(this.a,\"startForwardChannel_\");if(1==this.F)if(a)H(this.a,\"Not supposed to retry the open\");else{G(this.a,\"open_()\");this.R=Math.floor(1E5*Math.random());a=this.R++;var b=new L(this,this.a,a,void 0),c=this.i;this.L&&(c?(c=Fa(c),Ha(c,this.L)):c=this.L);null===this.h&&(b.j=c);var d=He(this,b),e=M(this.D);R(e,\"RID\",a);R(e,\"CVER\",22);this.o&&this.j&&R(e,\"X-HTTP-Session-Id\",this.j);Ae(this,e);this.h&&c&&we(e,this.h,c);be(this.c,b);this.va?(R(e,\"$req\",d),R(e,\"SID\",\"null\"),\nb.X=!0,Uc(b,e,null)):Uc(b,e,d);this.F=2}else 3==this.F&&(a?Ie(this,a):0==this.g.length?G(this.a,\"startForwardChannel_ returned: nothing to send\"):ce(this.c)?H(this.a,\"startForwardChannel_ returned: connection already in progress\"):(Ie(this),G(this.a,\"startForwardChannel_ finished, sent request\")))};\nfunction Ie(a,b){var c;b?c=b.c:c=a.R++;var d=M(a.D);R(d,\"SID\",a.J);R(d,\"RID\",c);R(d,\"AID\",a.N);Ae(a,d);a.h&&a.i&&we(d,a.h,a.i);c=new L(a,a.a,c,a.v+1);null===a.h&&(c.j=a.i);b&&(a.g=b.u.concat(a.g));b=He(a,c);c.setTimeout(1E4+Math.round(1E4*Math.random()));be(a.c,c);Uc(c,d,b)}function Ae(a,b){a.f&&ld({},function(a,d){R(b,d,a)})}\nfunction He(a,b){var c=Math.min(a.g.length,1E3),d=a.f?q(a.f.Wa,a.f,a):null;a:for(var e=a.g,f=-1;;){var h=[\"count=\"+c];-1==f?0I)f=Math.max(0,e[v].a-100),m=!1;else try{je(W,h,\"req\"+I+\"_\")}catch(Lb){d&&d(W)}}if(m){d=h.join(\"&\");break a}}a=a.g.splice(0,c);b.u=a;return d}function Je(a){if(!a.b&&!a.l){a.T=1;var b=a.Oa;Tb||Ub();Wb||(Tb(),Wb=!0);Pb.add(b,a);a.B=0}}\nfunction Ke(a){if(a.b||a.l)return H(a.a,\"Request already in progress\"),!1;if(3<=a.B)return!1;G(a.a,\"Going to retry GET\");a.T++;a.l=Dc(q(a.Oa,a),Ge(a,a.B));a.B++;return!0}\ng.Oa=function(){this.l=null;G(this.a,\"Creating new HttpRequest\");this.b=new L(this,this.a,\"rpc\",this.T);null===this.h&&(this.b.j=this.i);this.b.N=0;var a=M(this.ua);R(a,\"RID\",\"rpc\");R(a,\"SID\",this.J);R(a,\"CI\",this.ka?\"0\":\"1\");R(a,\"AID\",this.N);Ae(this,a);R(a,\"TYPE\",\"xmlhttp\");this.h&&this.i&&we(a,this.h,this.i);this.G&&this.b.setTimeout(this.G);Xc(this.b,a,!0,this.X);G(this.a,\"New Request created\")};\nfunction Sd(a,b,c){G(a.a,\"Test Connection Finished\");var d=b.l;d&&ae(a.c,d);a.ka=c;a.u=b.f;G(a.a,\"connectChannel_()\");a.D=Le(a,a.ja);Ee(a)}function Ud(a,b){G(a.a,\"Test Connection Failed\");a.u=b.f;V(a,2)}\ng.Na=function(a,b){if(0!=this.F&&(this.b==a||de(this.c,a)))if(this.u=a.C,!a.v&&de(this.c,a)&&3==this.F){try{var c=this.la.a.parse(b)}catch(f){c=null}if(n(c)&&3==c.length)if(b=c,0==b[0])a:if(G(this.a,\"Server claims our backchannel is missing.\"),this.l)G(this.a,\"But we are currently starting the request.\");else{if(this.b)if(this.b.D+3E3b&&this.ka&&0==this.B&&!this.s&&(this.s=Dc(q(this.cb,this),6E3)));else G(this.a,\"Bad POST response data returned\"),V(this,11)}else if((a.v||this.b==a)&&Ce(this),!xa(b))for(b=c=this.la.a.parse(b),c=0;cthis.c)throw Error(Ye);this.a=new Ue;this.b=new Wd;this.g=null;this.aa()}t(Xe,u);var Ye=\"[goog.structs.Pool] Min can not be greater than max\";g=Xe.prototype;g.da=function(){var a=r();if(!(null!=this.g&&0>a-this.g)){for(var b;0this.c&&0=this.a.length){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c}bf.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d=e)f=void 0;else{if(1==e)ua(d);else{d[0]=d.pop();d=0;c=c.a;e=c.length;for(var h=c[d];d>1;){var m=2*d+1,v=2*d+2;m=vh.a)break;c[d]=c[m];d=m}c[d]=h}f=f.b}f.apply(this,[b])}else break}};\ng.ma=function(a){Y.H.ma.call(this,a);this.ra()};g.aa=function(){Y.H.aa.call(this);this.ra()};g.w=function(){Y.H.w.call(this);k.clearTimeout(void 0);ua(this.f.a);this.f=null};function Z(a,b,c,d){this.l=a;this.j=!!d;Y.call(this,b,c)}t(Z,Y);Z.prototype.pa=function(){var a=new T,b=this.l;b&&b.forEach(function(b,d){a.headers.set(d,b)});this.j&&(a.o=!0);return a};Z.prototype.sa=function(a){return!a.i&&!a.a};Pe.prototype.createWebChannel=Pe.prototype.a;X.prototype.send=X.prototype.ab;X.prototype.open=X.prototype.$a;X.prototype.close=X.prototype.close;Ec.NO_ERROR=0;Ec.TIMEOUT=8;Ec.HTTP_ERROR=6;Fc.COMPLETE=\"complete\";Gc.EventType=Hc;Hc.OPEN=\"a\";Hc.CLOSE=\"b\";Hc.ERROR=\"c\";Hc.MESSAGE=\"d\";A.prototype.listen=A.prototype.Ha;Z.prototype.getObject=Z.prototype.da;Z.prototype.releaseObject=Z.prototype.jb;T.prototype.listenOnce=T.prototype.Ia;T.prototype.getLastError=T.prototype.bb;T.prototype.getLastErrorCode=T.prototype.Fa;\nT.prototype.getStatus=T.prototype.W;T.prototype.getStatusText=T.prototype.Ga;T.prototype.getResponseJson=T.prototype.Za;T.prototype.getResponseText=T.prototype.V;T.prototype.getResponseText=T.prototype.V;T.prototype.send=T.prototype.fa;module.exports={createWebChannelTransport:Te,ErrorCode:Ec,EventType:Fc,WebChannel:Gc,XhrIoPool:Z};}).call(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../webchannel-wrapper/dist/index.js\n// module id = 117\n// module chunks = 1","/**\n * Copyright 2017 Google Inc.\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 */\nimport { instances } from './src/logger';\nexport function setLogLevel(level) {\n instances.forEach(function (inst) {\n inst.logLevel = level;\n });\n}\nexport { Logger, LogLevel } from './src/logger';\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 container for all of the Logger instances\n */\nexport var instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n/**\n * The default log level\n */\nvar defaultLogLevel = LogLevel.INFO;\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nvar defaultLogHandler = function (instance, logType) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (logType < instance.logLevel)\n return;\n var now = new Date().toISOString();\n switch (logType) {\n /**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\n case LogLevel.DEBUG:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.VERBOSE:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.INFO:\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.WARN:\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.ERROR:\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n default:\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\n }\n};\nvar Logger = /** @class */ (function () {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n function Logger(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The log handler for the Logger instance.\n */\n this._logHandler = defaultLogHandler;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n Object.defineProperty(Logger.prototype, \"logLevel\", {\n get: function () {\n return this._logLevel;\n },\n set: function (val) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Logger.prototype, \"logHandler\", {\n get: function () {\n return this._logHandler;\n },\n set: function (val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The functions below are all based on the `console` interface\n */\n Logger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\n };\n Logger.prototype.log = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\n };\n Logger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\n };\n Logger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\n };\n Logger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\n };\n return Logger;\n}());\nexport { Logger };\n\n//# sourceMappingURL=logger.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/src/logger.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file diff --git a/lib/firebase/firebase-functions.js b/lib/firebase/firebase-functions.js new file mode 100644 index 00000000..9697c510 --- /dev/null +++ b/lib/firebase/firebase-functions.js @@ -0,0 +1,7 @@ +/*! + * @license Firebase v4.12.0 + * Build: rev-ef14d4f + * Terms: https://firebase.google.com/terms/ + */ +try{webpackJsonpFirebase([4],{118:function(e,t,n){n(119)},119:function(e,t,n){"use strict";function r(e){if(e>=200&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}function o(e,t,n){var o=r(e),i=o,a=void 0;try{var s=t.error;if(s){var u=s.status;if("string"==typeof u){if(!d[u])return new f("internal","internal");o=d[u]}i=u;var c=s.message;"string"==typeof c&&(i=c),void 0!==(a=s.details)&&(a=n.decode(a))}}catch(e){}return"ok"===o?null:new f(o,i,a)}function i(e,t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function a(e,t,n){return new h(e,n)}function s(e){var t={Functions:h};e.INTERNAL.registerService(v,a,t,void 0,!0)}Object.defineProperty(t,"__esModule",{value:!0});var u=n(7),c=n(2),d={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},f=function(e){function t(n,r,o){var i=e.call(this,r)||this;return Object.setPrototypeOf(i,t.prototype),i.code=n,i.details=o,i}return c.__extends(t,e),t}(Error),l=function(){function e(e){this.app=e}return e.prototype.getAuthToken=function(){return c.__awaiter(this,void 0,void 0,function(){var e,t;return c.__generator(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.app.INTERNAL.getToken()];case 1:return e=n.sent(),e?[2,e.accessToken]:[2,void 0];case 2:return t=n.sent(),[2,void 0];case 3:return[2]}})})},e.prototype.getInstanceIdToken=function(){return c.__awaiter(this,void 0,void 0,function(){var e,t,n;return c.__generator(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),this.app.messaging?(e=this.app.messaging(),[4,e.getToken()]):[2,void 0];case 1:return t=r.sent(),t?[2,t]:[2,void 0];case 2:return n=r.sent(),[2,void 0];case 3:return[2]}})})},e.prototype.getContext=function(){return c.__awaiter(this,void 0,void 0,function(){var e,t;return c.__generator(this,function(n){switch(n.label){case 0:return[4,this.getAuthToken()];case 1:return e=n.sent(),[4,this.getInstanceIdToken()];case 2:return t=n.sent(),[2,{authToken:e,instanceIdToken:t}]}})})},e}(),p=function(){function e(){}return e.prototype.encode=function(e){var t=this;if(null===e||void 0===e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===toString.call(e))return e;if(Array.isArray(e))return e.map(function(e){return t.encode(e)});if("function"==typeof e||"object"==typeof e)return i(e,function(e){return t.encode(e)});throw Error("Data cannot be encoded in JSON: "+e)},e.prototype.decode=function(e){var t=this;if(null===e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":var n=parseFloat(e.value);if(isNaN(n))throw Error("Data cannot be decoded from JSON: "+e);return n;default:throw Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(function(e){return t.decode(e)}):"function"==typeof e||"object"==typeof e?i(e,function(e){return t.decode(e)}):e},e}(),h=function(){function e(e,t){void 0===t&&(t="us-central1"),this.e=e,this.t=t,this.serializer=new p,this.contextProvider=new l(e)}return Object.defineProperty(e.prototype,"app",{get:function(){return this.e},enumerable:!0,configurable:!0}),e.prototype.n=function(e){var t=this.e.options.projectId;return"https://"+this.t+"-"+t+".cloudfunctions.net/"+e},e.prototype.httpsCallable=function(e){var t=this;return function(n){return t.call(e,n)}},e.prototype.postJSON=function(e,t,n){return c.__awaiter(this,void 0,void 0,function(){var r,o,i,a;return c.__generator(this,function(s){switch(s.label){case 0:n.append("Content-Type","application/json"),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,fetch(e,{method:"POST",body:JSON.stringify(t),headers:n})];case 2:return r=s.sent(),[3,4];case 3:return o=s.sent(),[2,{status:0,json:null}];case 4:i=null,s.label=5;case 5:return s.trys.push([5,7,,8]),[4,r.json()];case 6:return i=s.sent(),[3,8];case 7:return a=s.sent(),[3,8];case 8:return[2,{status:r.status,json:i}]}})})},e.prototype.call=function(e,t){return c.__awaiter(this,void 0,void 0,function(){var n,r,i,a,s,u,d,l;return c.__generator(this,function(c){switch(c.label){case 0:return n=this.n(e),t=this.serializer.encode(t),r={data:t},i=new Headers,[4,this.contextProvider.getContext()];case 1:return a=c.sent(),a.authToken&&i.append("Authorization","Bearer "+a.authToken),a.instanceIdToken&&i.append("Firebase-Instance-ID-Token",a.instanceIdToken),[4,this.postJSON(n,r,i)];case 2:if(s=c.sent(),u=o(s.status,s.json,this.serializer))throw u;if(!s.json)throw new f("internal","Response is not valid JSON object.");if(d=s.json.data,void 0===d&&(d=s.json.result),void 0===d)throw new f("internal","Response is missing data field.");return l=this.serializer.decode(d),[2,{data:l}]}})})},e}();t.registerFunctions=s;var v="functions";s(u.default)}},[118])}catch(e){throw Error("Cannot instantiate firebase-functions.js - be sure to load firebase-app.js first.")} +//# sourceMappingURL=firebase-functions.js.map \ No newline at end of file diff --git a/lib/firebase/firebase-functions.js.map b/lib/firebase/firebase-functions.js.map new file mode 100644 index 00000000..c5a90f5e --- /dev/null +++ b/lib/firebase/firebase-functions.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///firebase-functions.js","webpack:///./functions/index.js","webpack:///../functions/dist/esm/src/api/error.js","webpack:///../functions/dist/esm/src/serializer.js","webpack:///../functions/dist/esm/index.js","webpack:///../functions/dist/esm/src/context.js","webpack:///../functions/dist/esm/src/api/service.js"],"names":["webpackJsonpFirebase","118","module","exports","__webpack_require__","119","__webpack_exports__","codeForHTTPStatus","status","_errorForResponse","bodyJSON","serializer","code","description","details","undefined","errorJSON","error","status_1","errorCodeMap","error_HttpsErrorImpl","message","decode","e","mapValues","o","f","result","key","hasOwnProperty","factory","app","unused","region","service_Service","registerFunctions","instance","namespaceExports","Functions","INTERNAL","registerService","FUNCTIONS_TYPE","Object","defineProperty","value","esm","tslib_es6","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","UNAUTHENTICATED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","_super","HttpsErrorImpl","_this","call","this","setPrototypeOf","prototype","Error","context_ContextProvider","ContextProvider","getAuthToken","token","e_1","_a","label","trys","push","getToken","sent","accessToken","getInstanceIdToken","messaging","e_2","getContext","authToken","instanceIdToken","Serializer","encode","data","Number","valueOf","isFinite","toString","Array","isArray","map","x","json","parseFloat","isNaN","Service","app_","region_","contextProvider","get","enumerable","configurable","_url","name","projectId","options","httpsCallable","postJSON","url","body","headers","response","append","fetch","method","JSON","stringify","context","responseData","decodedData","Headers"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IAExBC,IACA,SAAUC,EAAQC,EAASC,GCOjCA,EAAA,MDgBMC,IACA,SAAUH,EAAQI,EAAqBF,GAE7C,YEkCA,SAAAG,GAAAC,GAEA,GAAAA,GAAA,KAAAA,EAAA,IACA,UAEA,QAAAA,GACA,OAEA,gBACA,UACA,wBACA,UACA,uBACA,UACA,yBACA,UAC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,GACA0B,GAAgC1B,QAChC2B,EAAA,GAAAU,UACA,EAAA7D,KAAAuC,gBAAApB,aACA,QAQA,MAPAuC,GAAAjD,EAAAK,OACA4C,EAAAtC,WACA+B,EAAAE,OAAA,0BAAAK,EAAAtC,WAEAsC,EAAArC,iBACA8B,EAAAE,OAAA,6BAAAK,EAAArC,kBAEA,EAAArB,KAAAgD,SAAAC,EAAAC,EAAAC,GACA,QAGA,GAFAC,EAAA3C,EAAAK,OACAhE,EAAAR,EAAA8G,EAAA/G,OAAA+G,EAAAnB,KAAAjC,KAAAxD,YAEA,KAAAM,EAEA,KAAAsG,EAAAnB,KACA,SAAAhF,GAAA,gDAQA,IANA0G,EAAAP,EAAAnB,KAAAT,SAGA,KAAAmC,IACAA,EAAAP,EAAAnB,KAAAzE,YAEA,KAAAmG,EAEA,SAAA1G,GAAA,6CAGA,OADA2G,GAAA5D,KAAAxD,WAAAW,OAAAwG,IACA,GAA+CnC,KAAAoC,UAK/CxB,IFxKAjG,GAAA,kBAAA6B,CAoBA,IAAAM,GAAA,WAeAN,GAAAU,EAAA,YJqjBG,MACO,MAAM5B,GACN,KAAUqD,OACR","file":"firebase-functions.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([4],{\n\n/***/ 118:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(119);\n\n\n/***/ }),\n\n/***/ 119:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// EXTERNAL MODULE: /tmp/tmp-208812ou3wR5n5ZCvd/node_modules/tslib/tslib.es6.js\nvar tslib_es6 = __webpack_require__(2);\n\n// CONCATENATED MODULE: ../functions/dist/esm/src/api/error.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Standard error codes for different ways a request can fail, as defined by:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * This map is used primarily to convert from a backend error code string to\n * a client SDK error code string, and make sure it's in the supported set.\n */\nvar errorCodeMap = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n/**\n * An explicit error that can be thrown from a handler to send an error to the\n * client that called the function.\n */\nvar error_HttpsErrorImpl = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](HttpsErrorImpl, _super);\n function HttpsErrorImpl(code, message, details) {\n var _this = _super.call(this, message) || this;\n // This is a workaround for a bug in TypeScript when extending Error:\n // tslint:disable-next-line\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(_this, HttpsErrorImpl.prototype);\n _this.code = code;\n _this.details = details;\n return _this;\n }\n return HttpsErrorImpl;\n}(Error));\n\n/**\n * Takes an HTTP status code and returns the corresponding ErrorCode.\n * This is the standard HTTP status code -> error mapping defined in:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * @param status An HTTP status code.\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\n */\nfunction codeForHTTPStatus(status) {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n case 400:\n return 'invalid-argument';\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission-denied';\n case 404:\n return 'not-found';\n case 409:\n return 'aborted';\n case 429:\n return 'resource-exhausted';\n case 499:\n return 'cancelled';\n case 500:\n return 'internal';\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline-exceeded';\n }\n return 'unknown';\n}\n/**\n * Takes an HTTP response and returns the corresponding Error, if any.\n */\nfunction _errorForResponse(status, bodyJSON, serializer) {\n var code = codeForHTTPStatus(status);\n // Start with reasonable defaults from the status code.\n var description = code;\n var details = undefined;\n // Then look through the body for explicit details.\n try {\n var errorJSON = bodyJSON.error;\n if (errorJSON) {\n var status_1 = errorJSON.status;\n if (typeof status_1 === 'string') {\n if (!errorCodeMap[status_1]) {\n // They must've included an unknown error code in the body.\n return new error_HttpsErrorImpl('internal', 'internal');\n }\n code = errorCodeMap[status_1];\n }\n // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n description = status_1;\n var message = errorJSON.message;\n if (typeof message === 'string') {\n description = message;\n }\n details = errorJSON.details;\n if (details !== undefined) {\n details = serializer.decode(details);\n }\n }\n }\n catch (e) {\n // If we couldn't parse explicit error data, that's fine.\n }\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n return new error_HttpsErrorImpl(code, description, details);\n}\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../functions/dist/esm/src/context.js\n\n/**\n * Helper class to get metadata that should be included with a function call.\n */\nvar context_ContextProvider = /** @class */ (function () {\n function ContextProvider(app) {\n this.app = app;\n }\n ContextProvider.prototype.getAuthToken = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var token, e_1;\n return tslib_es6[\"__generator\"](this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, this.app.INTERNAL.getToken()];\n case 1:\n token = _a.sent();\n if (!token) {\n return [2 /*return*/, undefined];\n }\n return [2 /*return*/, token.accessToken];\n case 2:\n e_1 = _a.sent();\n // If there's any error when trying to get the auth token, leave it off.\n return [2 /*return*/, undefined];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n ContextProvider.prototype.getInstanceIdToken = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var messaging, token, e_2;\n return tslib_es6[\"__generator\"](this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n // HACK: Until we have a separate instanceId package, this is a quick way\n // to load in the messaging instance for this app.\n if (!this.app.messaging) {\n return [2 /*return*/, undefined];\n }\n messaging = this.app.messaging();\n return [4 /*yield*/, messaging.getToken()];\n case 1:\n token = _a.sent();\n if (!token) {\n return [2 /*return*/, undefined];\n }\n return [2 /*return*/, token];\n case 2:\n e_2 = _a.sent();\n // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n // If there's any error when trying to get the token, leave it off.\n return [2 /*return*/, undefined];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n ContextProvider.prototype.getContext = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var authToken, instanceIdToken;\n return tslib_es6[\"__generator\"](this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.getAuthToken()];\n case 1:\n authToken = _a.sent();\n return [4 /*yield*/, this.getInstanceIdToken()];\n case 2:\n instanceIdToken = _a.sent();\n return [2 /*return*/, { authToken: authToken, instanceIdToken: instanceIdToken }];\n }\n });\n });\n };\n return ContextProvider;\n}());\n\n\n//# sourceMappingURL=context.js.map\n\n// CONCATENATED MODULE: ../functions/dist/esm/src/serializer.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nvar UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\nfunction mapValues(o, f) {\n var result = {};\n for (var key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n return result;\n}\nvar Serializer = /** @class */ (function () {\n function Serializer() {\n }\n // Takes data and encodes it in a JSON-friendly way, such that types such as\n // Date are preserved.\n Serializer.prototype.encode = function (data) {\n var _this = this;\n if (data === null || data === undefined) {\n return null;\n }\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (data === true || data === false) {\n return data;\n }\n if (toString.call(data) === '[object String]') {\n return data;\n }\n if (Array.isArray(data)) {\n return data.map(function (x) { return _this.encode(x); });\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data, function (x) { return _this.encode(x); });\n }\n // If we got this far, the data is not encodable.\n throw new Error('Data cannot be encoded in JSON: ' + data);\n };\n // Takes data that's been encoded in a JSON-friendly form and returns a form\n // with richer datatypes, such as Dates, etc.\n Serializer.prototype.decode = function (json) {\n var _this = this;\n if (json === null) {\n return json;\n }\n if (json['@type']) {\n switch (json['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n var value = parseFloat(json.value);\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n return value;\n }\n default: {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n if (Array.isArray(json)) {\n return json.map(function (x) { return _this.decode(x); });\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json, function (x) { return _this.decode(x); });\n }\n // Anything else is safe to return.\n return json;\n };\n return Serializer;\n}());\n\n\n//# sourceMappingURL=serializer.js.map\n\n// CONCATENATED MODULE: ../functions/dist/esm/src/api/service.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n/**\n * The main class for the Firebase Functions SDK.\n */\nvar service_Service = /** @class */ (function () {\n /**\n * Creates a new Functions service for the given app and (optional) region.\n * @param app_ The FirebaseApp to use.\n * @param region_ The region to call functions in.\n */\n function Service(app_, region_) {\n if (region_ === void 0) { region_ = 'us-central1'; }\n this.app_ = app_;\n this.region_ = region_;\n this.serializer = new Serializer();\n this.contextProvider = new context_ContextProvider(app_);\n }\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the URL for a callable with the given name.\n * @param name The name of the callable.\n */\n Service.prototype._url = function (name) {\n var projectId = this.app_.options.projectId;\n var region = this.region_;\n return \"https://\" + region + \"-\" + projectId + \".cloudfunctions.net/\" + name;\n };\n /**\n * Returns a reference to the callable https trigger with the given name.\n * @param name The name of the trigger.\n */\n Service.prototype.httpsCallable = function (name) {\n var _this = this;\n var callable = function (data) {\n return _this.call(name, data);\n };\n return callable;\n };\n /**\n * Does an HTTP POST and returns the completed response.\n * @param url The url to post to.\n * @param body The JSON body of the post.\n * @param headers The HTTP headers to include in the request.\n * @return A Promise that will succeed when the request finishes.\n */\n Service.prototype.postJSON = function (url, body, headers) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var response, e_1, json, e_2;\n return tslib_es6[\"__generator\"](this, function (_a) {\n switch (_a.label) {\n case 0:\n headers.append('Content-Type', 'application/json');\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: headers\n })];\n case 2:\n response = _a.sent();\n return [3 /*break*/, 4];\n case 3:\n e_1 = _a.sent();\n // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to no, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n return [2 /*return*/, {\n status: 0,\n json: null\n }];\n case 4:\n json = null;\n _a.label = 5;\n case 5:\n _a.trys.push([5, 7, , 8]);\n return [4 /*yield*/, response.json()];\n case 6:\n json = _a.sent();\n return [3 /*break*/, 8];\n case 7:\n e_2 = _a.sent();\n return [3 /*break*/, 8];\n case 8: return [2 /*return*/, {\n status: response.status,\n json: json\n }];\n }\n });\n });\n };\n /**\n * Calls a callable function asynchronously and returns the result.\n * @param name The name of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\n Service.prototype.call = function (name, data) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var url, body, headers, context, response, error, responseData, decodedData;\n return tslib_es6[\"__generator\"](this, function (_a) {\n switch (_a.label) {\n case 0:\n url = this._url(name);\n // Encode any special types, such as dates, in the input data.\n data = this.serializer.encode(data);\n body = { data: data };\n headers = new Headers();\n return [4 /*yield*/, this.contextProvider.getContext()];\n case 1:\n context = _a.sent();\n if (context.authToken) {\n headers.append('Authorization', 'Bearer ' + context.authToken);\n }\n if (context.instanceIdToken) {\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\n }\n return [4 /*yield*/, this.postJSON(url, body, headers)];\n case 2:\n response = _a.sent();\n error = _errorForResponse(response.status, response.json, this.serializer);\n if (error) {\n throw error;\n }\n if (!response.json) {\n throw new error_HttpsErrorImpl('internal', 'Response is not valid JSON object.');\n }\n responseData = response.json.data;\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new error_HttpsErrorImpl('internal', 'Response is missing data field.');\n }\n decodedData = this.serializer.decode(responseData);\n return [2 /*return*/, { data: decodedData }];\n }\n });\n });\n };\n return Service;\n}());\n\n\n//# sourceMappingURL=service.js.map\n\n// CONCATENATED MODULE: ../functions/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerFunctions\"] = registerFunctions;\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * Type constant for Firebase Functions.\n */\nvar FUNCTIONS_TYPE = 'functions';\nfunction factory(app, unused, region) {\n return new service_Service(app, region);\n}\nfunction registerFunctions(instance) {\n var namespaceExports = {\n // no-inline\n Functions: service_Service\n };\n instance.INTERNAL.registerService(FUNCTIONS_TYPE, factory, namespaceExports, \n // We don't need to wait on any AppHooks.\n undefined, \n // Allow multiple functions instances per app.\n true);\n}\nregisterFunctions(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[118]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-functions.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-functions.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/functions');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./functions/index.js\n// module id = 118\n// module chunks = 4","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\n/**\n * Standard error codes for different ways a request can fail, as defined by:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * This map is used primarily to convert from a backend error code string to\n * a client SDK error code string, and make sure it's in the supported set.\n */\nvar errorCodeMap = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n/**\n * An explicit error that can be thrown from a handler to send an error to the\n * client that called the function.\n */\nvar HttpsErrorImpl = /** @class */ (function (_super) {\n tslib_1.__extends(HttpsErrorImpl, _super);\n function HttpsErrorImpl(code, message, details) {\n var _this = _super.call(this, message) || this;\n // This is a workaround for a bug in TypeScript when extending Error:\n // tslint:disable-next-line\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(_this, HttpsErrorImpl.prototype);\n _this.code = code;\n _this.details = details;\n return _this;\n }\n return HttpsErrorImpl;\n}(Error));\nexport { HttpsErrorImpl };\n/**\n * Takes an HTTP status code and returns the corresponding ErrorCode.\n * This is the standard HTTP status code -> error mapping defined in:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * @param status An HTTP status code.\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\n */\nfunction codeForHTTPStatus(status) {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n case 400:\n return 'invalid-argument';\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission-denied';\n case 404:\n return 'not-found';\n case 409:\n return 'aborted';\n case 429:\n return 'resource-exhausted';\n case 499:\n return 'cancelled';\n case 500:\n return 'internal';\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline-exceeded';\n }\n return 'unknown';\n}\n/**\n * Takes an HTTP response and returns the corresponding Error, if any.\n */\nexport function _errorForResponse(status, bodyJSON, serializer) {\n var code = codeForHTTPStatus(status);\n // Start with reasonable defaults from the status code.\n var description = code;\n var details = undefined;\n // Then look through the body for explicit details.\n try {\n var errorJSON = bodyJSON.error;\n if (errorJSON) {\n var status_1 = errorJSON.status;\n if (typeof status_1 === 'string') {\n if (!errorCodeMap[status_1]) {\n // They must've included an unknown error code in the body.\n return new HttpsErrorImpl('internal', 'internal');\n }\n code = errorCodeMap[status_1];\n }\n // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n description = status_1;\n var message = errorJSON.message;\n if (typeof message === 'string') {\n description = message;\n }\n details = errorJSON.details;\n if (details !== undefined) {\n details = serializer.decode(details);\n }\n }\n }\n catch (e) {\n // If we couldn't parse explicit error data, that's fine.\n }\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n return new HttpsErrorImpl(code, description, details);\n}\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../functions/dist/esm/src/api/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nvar LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nvar UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\nfunction mapValues(o, f) {\n var result = {};\n for (var key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n return result;\n}\nvar Serializer = /** @class */ (function () {\n function Serializer() {\n }\n // Takes data and encodes it in a JSON-friendly way, such that types such as\n // Date are preserved.\n Serializer.prototype.encode = function (data) {\n var _this = this;\n if (data === null || data === undefined) {\n return null;\n }\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (data === true || data === false) {\n return data;\n }\n if (toString.call(data) === '[object String]') {\n return data;\n }\n if (Array.isArray(data)) {\n return data.map(function (x) { return _this.encode(x); });\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data, function (x) { return _this.encode(x); });\n }\n // If we got this far, the data is not encodable.\n throw new Error('Data cannot be encoded in JSON: ' + data);\n };\n // Takes data that's been encoded in a JSON-friendly form and returns a form\n // with richer datatypes, such as Dates, etc.\n Serializer.prototype.decode = function (json) {\n var _this = this;\n if (json === null) {\n return json;\n }\n if (json['@type']) {\n switch (json['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n var value = parseFloat(json.value);\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n return value;\n }\n default: {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n if (Array.isArray(json)) {\n return json.map(function (x) { return _this.decode(x); });\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json, function (x) { return _this.decode(x); });\n }\n // Anything else is safe to return.\n return json;\n };\n return Serializer;\n}());\nexport { Serializer };\n\n//# sourceMappingURL=serializer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../functions/dist/esm/src/serializer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport { Service } from './src/api/service';\n/**\n * Type constant for Firebase Functions.\n */\nvar FUNCTIONS_TYPE = 'functions';\nfunction factory(app, unused, region) {\n return new Service(app, region);\n}\nexport function registerFunctions(instance) {\n var namespaceExports = {\n // no-inline\n Functions: Service\n };\n instance.INTERNAL.registerService(FUNCTIONS_TYPE, factory, namespaceExports, \n // We don't need to wait on any AppHooks.\n undefined, \n // Allow multiple functions instances per app.\n true);\n}\nregisterFunctions(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../functions/dist/esm/index.js\n// module id = null\n// module chunks = ","import * as tslib_1 from \"tslib\";\n/**\n * Helper class to get metadata that should be included with a function call.\n */\nvar ContextProvider = /** @class */ (function () {\n function ContextProvider(app) {\n this.app = app;\n }\n ContextProvider.prototype.getAuthToken = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var token, e_1;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, this.app.INTERNAL.getToken()];\n case 1:\n token = _a.sent();\n if (!token) {\n return [2 /*return*/, undefined];\n }\n return [2 /*return*/, token.accessToken];\n case 2:\n e_1 = _a.sent();\n // If there's any error when trying to get the auth token, leave it off.\n return [2 /*return*/, undefined];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n ContextProvider.prototype.getInstanceIdToken = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var messaging, token, e_2;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n // HACK: Until we have a separate instanceId package, this is a quick way\n // to load in the messaging instance for this app.\n if (!this.app.messaging) {\n return [2 /*return*/, undefined];\n }\n messaging = this.app.messaging();\n return [4 /*yield*/, messaging.getToken()];\n case 1:\n token = _a.sent();\n if (!token) {\n return [2 /*return*/, undefined];\n }\n return [2 /*return*/, token];\n case 2:\n e_2 = _a.sent();\n // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n // If there's any error when trying to get the token, leave it off.\n return [2 /*return*/, undefined];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n ContextProvider.prototype.getContext = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var authToken, instanceIdToken;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.getAuthToken()];\n case 1:\n authToken = _a.sent();\n return [4 /*yield*/, this.getInstanceIdToken()];\n case 2:\n instanceIdToken = _a.sent();\n return [2 /*return*/, { authToken: authToken, instanceIdToken: instanceIdToken }];\n }\n });\n });\n };\n return ContextProvider;\n}());\nexport { ContextProvider };\n\n//# sourceMappingURL=context.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../functions/dist/esm/src/context.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as tslib_1 from \"tslib\";\nimport { _errorForResponse, HttpsErrorImpl } from './error';\nimport { ContextProvider } from '../context';\nimport { Serializer } from '../serializer';\n/**\n * The main class for the Firebase Functions SDK.\n */\nvar Service = /** @class */ (function () {\n /**\n * Creates a new Functions service for the given app and (optional) region.\n * @param app_ The FirebaseApp to use.\n * @param region_ The region to call functions in.\n */\n function Service(app_, region_) {\n if (region_ === void 0) { region_ = 'us-central1'; }\n this.app_ = app_;\n this.region_ = region_;\n this.serializer = new Serializer();\n this.contextProvider = new ContextProvider(app_);\n }\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the URL for a callable with the given name.\n * @param name The name of the callable.\n */\n Service.prototype._url = function (name) {\n var projectId = this.app_.options.projectId;\n var region = this.region_;\n return \"https://\" + region + \"-\" + projectId + \".cloudfunctions.net/\" + name;\n };\n /**\n * Returns a reference to the callable https trigger with the given name.\n * @param name The name of the trigger.\n */\n Service.prototype.httpsCallable = function (name) {\n var _this = this;\n var callable = function (data) {\n return _this.call(name, data);\n };\n return callable;\n };\n /**\n * Does an HTTP POST and returns the completed response.\n * @param url The url to post to.\n * @param body The JSON body of the post.\n * @param headers The HTTP headers to include in the request.\n * @return A Promise that will succeed when the request finishes.\n */\n Service.prototype.postJSON = function (url, body, headers) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var response, e_1, json, e_2;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n headers.append('Content-Type', 'application/json');\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: headers\n })];\n case 2:\n response = _a.sent();\n return [3 /*break*/, 4];\n case 3:\n e_1 = _a.sent();\n // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to no, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n return [2 /*return*/, {\n status: 0,\n json: null\n }];\n case 4:\n json = null;\n _a.label = 5;\n case 5:\n _a.trys.push([5, 7, , 8]);\n return [4 /*yield*/, response.json()];\n case 6:\n json = _a.sent();\n return [3 /*break*/, 8];\n case 7:\n e_2 = _a.sent();\n return [3 /*break*/, 8];\n case 8: return [2 /*return*/, {\n status: response.status,\n json: json\n }];\n }\n });\n });\n };\n /**\n * Calls a callable function asynchronously and returns the result.\n * @param name The name of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\n Service.prototype.call = function (name, data) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var url, body, headers, context, response, error, responseData, decodedData;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n url = this._url(name);\n // Encode any special types, such as dates, in the input data.\n data = this.serializer.encode(data);\n body = { data: data };\n headers = new Headers();\n return [4 /*yield*/, this.contextProvider.getContext()];\n case 1:\n context = _a.sent();\n if (context.authToken) {\n headers.append('Authorization', 'Bearer ' + context.authToken);\n }\n if (context.instanceIdToken) {\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\n }\n return [4 /*yield*/, this.postJSON(url, body, headers)];\n case 2:\n response = _a.sent();\n error = _errorForResponse(response.status, response.json, this.serializer);\n if (error) {\n throw error;\n }\n if (!response.json) {\n throw new HttpsErrorImpl('internal', 'Response is not valid JSON object.');\n }\n responseData = response.json.data;\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new HttpsErrorImpl('internal', 'Response is missing data field.');\n }\n decodedData = this.serializer.decode(responseData);\n return [2 /*return*/, { data: decodedData }];\n }\n });\n });\n };\n return Service;\n}());\nexport { Service };\n\n//# sourceMappingURL=service.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../functions/dist/esm/src/api/service.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file diff --git a/lib/firebase/firebase-messaging-externs.js b/lib/firebase/firebase-messaging-externs.js index 59f26afd..375cb5f3 100644 --- a/lib/firebase/firebase-messaging-externs.js +++ b/lib/firebase/firebase-messaging-externs.js @@ -1,5 +1,5 @@ /** - * Copyright 2017 Google Inc. + * @license Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/lib/firebase/firebase-messaging.js b/lib/firebase/firebase-messaging.js index f9f8cc83..400863e7 100644 --- a/lib/firebase/firebase-messaging.js +++ b/lib/firebase/firebase-messaging.js @@ -1,7 +1,7 @@ /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -try{webpackJsonpFirebase([3],{116:function(e,t,r){r(117)},117:function(e,t,r){"use strict";function n(e){var t=new Uint8Array(e);return window.btoa(String.fromCharCode.apply(null,t))}function o(e){var t=function(e){return self&&"ServiceWorkerGlobalScope"in self?new A(e):new k(e)},r={Messaging:k};e.INTERNAL.registerService("messaging",t,r)}Object.defineProperty(t,"__esModule",{value:!0});var i,s=r(0),a={AVAILABLE_IN_WINDOW:"only-available-in-window",AVAILABLE_IN_SW:"only-available-in-sw",SHOULD_BE_INHERITED:"should-be-overriden",BAD_SENDER_ID:"bad-sender-id",INCORRECT_GCM_SENDER_ID:"incorrect-gcm-sender-id",PERMISSION_DEFAULT:"permission-default",PERMISSION_BLOCKED:"permission-blocked",UNSUPPORTED_BROWSER:"unsupported-browser",NOTIFICATIONS_BLOCKED:"notifications-blocked",FAILED_DEFAULT_REGISTRATION:"failed-serviceworker-registration",SW_REGISTRATION_EXPECTED:"sw-registration-expected",GET_SUBSCRIPTION_FAILED:"get-subscription-failed",INVALID_SAVED_TOKEN:"invalid-saved-token",SW_REG_REDUNDANT:"sw-reg-redundant",TOKEN_SUBSCRIBE_FAILED:"token-subscribe-failed",TOKEN_SUBSCRIBE_NO_TOKEN:"token-subscribe-no-token",TOKEN_SUBSCRIBE_NO_PUSH_SET:"token-subscribe-no-push-set",USE_SW_BEFORE_GET_TOKEN:"use-sw-before-get-token",INVALID_DELETE_TOKEN:"invalid-delete-token",DELETE_TOKEN_NOT_FOUND:"delete-token-not-found",DELETE_SCOPE_NOT_FOUND:"delete-scope-not-found",BG_HANDLER_FUNCTION_EXPECTED:"bg-handler-function-expected",NO_WINDOW_CLIENT_TO_MSG:"no-window-client-to-msg",UNABLE_TO_RESUBSCRIBE:"unable-to-resubscribe",NO_FCM_TOKEN_FOR_RESUBSCRIBE:"no-fcm-token-for-resubscribe",FAILED_TO_DELETE_TOKEN:"failed-to-delete-token",NO_SW_IN_REG:"no-sw-in-reg",BAD_SCOPE:"bad-scope",BAD_VAPID_KEY:"bad-vapid-key",BAD_SUBSCRIPTION:"bad-subscription",BAD_TOKEN:"bad-token",BAD_PUSH_SET:"bad-push-set",FAILED_DELETE_VAPID_KEY:"failed-delete-vapid-key"},c=(i={},i[a.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",i[a.AVAILABLE_IN_SW]="This method is available in a service worker context.",i["should-be-overriden"]="This method should be overriden by extended classes.",i["bad-sender-id"]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",i["permission-default"]="The required permissions were not granted and dismissed instead.",i["permission-blocked"]="The required permissions were not granted and blocked instead.",i["unsupported-browser"]="This browser doesn't support the API's required to use the firebase SDK.",i["notifications-blocked"]="Notifications have been blocked.",i[a.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",i["sw-registration-expected"]="A service worker registration was the expected input.",i["get-subscription-failed"]="There was an error when trying to get any existing Push Subscriptions.",i["invalid-saved-token"]="Unable to access details of the saved token.",i["sw-reg-redundant"]="The service worker being used for push was made redundant.",i["token-subscribe-failed"]="A problem occured while subscribing the user to FCM: {$message}",i["token-subscribe-no-token"]="FCM returned no token when subscribing the user to push.",i["token-subscribe-no-push-set"]="FCM returned an invalid response when getting an FCM token.",i["use-sw-before-get-token"]="You must call useServiceWorker() before calling getToken() to ensure your service worker is used.",i["invalid-delete-token"]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",i["delete-token-not-found"]="The deletion attempt for token could not be performed as the token was not found.",i["delete-scope-not-found"]="The deletion attempt for service worker scope could not be performed as the scope was not found.",i["bg-handler-function-expected"]="The input to setBackgroundMessageHandler() must be a function.",i["no-window-client-to-msg"]="An attempt was made to message a non-existant window client.",i["unable-to-resubscribe"]="There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}",i["no-fcm-token-for-resubscribe"]="Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit.",i["failed-to-delete-token"]="Unable to delete the currently saved token.",i["no-sw-in-reg"]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",i["incorrect-gcm-sender-id"]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",i["bad-scope"]="The service worker scope must be a string with at least one character.",i["bad-vapid-key"]="The public VAPID key must be a string with at least one character.",i["bad-subscription"]="The subscription must be a valid PushSubscription.",i["bad-token"]="The FCM Token used for storage / lookup was not a valid token string.",i["bad-push-set"]="The FCM push set used for storage / lookup was not not a valid push set string.",i["failed-delete-vapid-key"]="The VAPID key could not be deleted.",i),u={codes:a,map:c},_=function(e){return n(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},d=[4,51,148,247,223,161,235,177,220,3,162,94,21,113,219,72,211,46,237,237,178,52,219,183,71,58,12,143,196,204,225,111,60,140,132,223,171,182,102,62,242,12,212,139,254,227,249,118,47,20,28,99,8,106,111,45,177,26,149,176,206,55,192,156,110],f={userVisibleOnly:!0,applicationServerKey:new Uint8Array(d)},h={ENDPOINT:"https://fcm.googleapis.com",APPLICATION_SERVER_KEY:d,SUBSCRIPTION_OPTIONS:f},p="fcm_token_object_Store",l=function(){function e(){this.e=new s.ErrorFactory("messaging","Messaging",u.map),this.t=null}return e.prototype.r=function(){return this.t?this.t:(this.t=new Promise(function(t,r){var n=indexedDB.open(e.DB_NAME,1);n.onerror=function(e){r(e.target.error)},n.onsuccess=function(e){t(e.target.result)},n.onupgradeneeded=function(e){var t=e.target.result,r=t.createObjectStore(p,{keyPath:"swScope"});r.createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0})}}),this.t)},e.prototype.closeDatabase=function(){var e=this;return this.t?this.t.then(function(t){t.close(),e.t=null}):Promise.resolve()},e.prototype.getTokenDetailsFromToken=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.index("fcmToken"),a=s.get(e);a.onerror=function(e){n(e.target.error)},a.onsuccess=function(e){r(e.target.result)}})})},e.prototype.n=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.get(e);s.onerror=function(e){n(e.target.error)},s.onsuccess=function(e){r(e.target.result)}})})},e.prototype.o=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=[],a=i.openCursor();a.onerror=function(e){n(e.target.error)},a.onsuccess=function(t){var n=t.target.result;n?(n.value.fcmSenderId===e&&s.push(n.value),n.continue()):r(s)}})})},e.prototype.subscribeToFCM=function(e,t,r){var n=this,o=_(t.getKey("p256dh")),i=_(t.getKey("auth")),s="authorized_entity="+e+"&endpoint="+t.endpoint+"&encryption_key="+o+"&encryption_auth="+i;r&&(s+="&pushSet="+r);var a=new Headers;a.append("Content-Type","application/x-www-form-urlencoded");var c={method:"POST",headers:a,body:s};return fetch(h.ENDPOINT+"/fcm/connect/subscribe",c).then(function(e){return e.json()}).then(function(e){var t=e;if(t.error){var r=t.error.message;throw n.e.create(u.codes.TOKEN_SUBSCRIBE_FAILED,{message:r})}if(!t.token)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_TOKEN);if(!t.pushSet)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);return{token:t.token,pushSet:t.pushSet}})},e.prototype.i=function(e,t){return e.endpoint===t.endpoint&&_(e.getKey("auth"))===t.auth&&_(e.getKey("p256dh"))===t.p256dh},e.prototype.s=function(e,t,r,n,o){var i={swScope:t.scope,endpoint:r.endpoint,auth:_(r.getKey("auth")),p256dh:_(r.getKey("p256dh")),fcmToken:n,fcmPushSet:o,fcmSenderId:e};return this.r().then(function(e){return new Promise(function(t,r){var n=e.transaction([p],"readwrite"),o=n.objectStore(p),s=o.put(i);s.onerror=function(e){r(e.target.error)},s.onsuccess=function(e){t()}})})},e.prototype.getSavedToken=function(e,t){var r=this;return t instanceof ServiceWorkerRegistration?"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.BAD_SENDER_ID)):this.o(e).then(function(r){if(0!==r.length){var n=r.findIndex(function(r){return t.scope===r.swScope&&e===r.fcmSenderId});if(-1!==n)return r[n]}}).then(function(e){if(e)return t.pushManager.getSubscription().catch(function(e){throw r.e.create(u.codes.GET_SUBSCRIPTION_FAILED)}).then(function(t){if(t&&r.i(t,e))return e.fcmToken})}):Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED))},e.prototype.createToken=function(e,t){var r=this;if("string"!=typeof e||0===e.length)return Promise.reject(this.e.create(u.codes.BAD_SENDER_ID));if(!(t instanceof ServiceWorkerRegistration))return Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED));var n,o;return t.pushManager.getSubscription().then(function(e){return e||t.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(t){return n=t,r.subscribeToFCM(e,n)}).then(function(i){return o=i,r.s(e,t,n,o.token,o.pushSet)}).then(function(){return o.token})},e.prototype.deleteToken=function(e){var t=this;return"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.INVALID_DELETE_TOKEN)):this.getTokenDetailsFromToken(e).then(function(e){if(!e)throw t.e.create(u.codes.DELETE_TOKEN_NOT_FOUND);return t.r().then(function(r){return new Promise(function(n,o){var i=r.transaction([p],"readwrite"),s=i.objectStore(p),a=s.delete(e.swScope);a.onerror=function(e){o(e.target.error)},a.onsuccess=function(r){if(0===r.target.result)return void o(t.e.create(u.codes.FAILED_TO_DELETE_TOKEN));n(e)}})})})},e}(),g=l,E="messagingSenderId",T=function(){function e(e){var t=this;if(this.e=new s.ErrorFactory("messaging","Messaging",u.map),!e.options[E]||"string"!=typeof e.options[E])throw this.e.create(u.codes.BAD_SENDER_ID);this.a=e.options[E],this.c=new g,this.app=e,this.INTERNAL={},this.INTERNAL.delete=function(){return t.delete}}return e.prototype.getToken=function(){var e=this,t=this.u();return"granted"!==t?"denied"===t?Promise.reject(this.e.create(u.codes.NOTIFICATIONS_BLOCKED)):Promise.resolve(null):this._().then(function(t){return e.c.getSavedToken(e.a,t).then(function(r){return r||e.c.createToken(e.a,t)})})},e.prototype.deleteToken=function(e){var t=this;return this.c.deleteToken(e).then(function(){return t._().then(function(e){if(e)return e.pushManager.getSubscription()}).then(function(e){if(e)return e.unsubscribe()})})},e.prototype._=function(){throw this.e.create(u.codes.SHOULD_BE_INHERITED)},e.prototype.requestPermission=function(){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.useServiceWorker=function(e){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onMessage=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onTokenRefresh=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.setBackgroundMessageHandler=function(e){throw this.e.create(u.codes.AVAILABLE_IN_SW)},e.prototype.delete=function(){return this.c.closeDatabase()},e.prototype.u=function(){return Notification.permission},e.prototype.getTokenManager=function(){return this.c},e}(),S=T,b={TYPE_OF_MSG:"firebase-messaging-msg-type",DATA:"firebase-messaging-msg-data"},v={PUSH_MSG_RECEIVED:"push-msg-received",NOTIFICATION_CLICKED:"notification-clicked"},I=function(e,t){return r={},r[b.TYPE_OF_MSG]=e,r[b.DATA]=t,r;var r},m={PARAMS:b,TYPES_OF_MSG:v,createNewMsg:I},y={path:"/firebase-messaging-sw.js",scope:"/firebase-cloud-messaging-push-scope"},N=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),w=function(e){function t(t){var r=e.call(this,t)||this;return r.d,r.f,r.h=null,r.p=Object(s.createSubscribe)(function(e){r.h=e}),r.l=null,r.g=Object(s.createSubscribe)(function(e){r.l=e}),r.T(),r}return N(t,e),t.prototype.getToken=function(){var t=this;return this.S()?this.b().then(function(){return e.prototype.getToken.call(t)}):Promise.reject(this.e.create(u.codes.UNSUPPORTED_BROWSER))},t.prototype.b=function(){var e=this;if(this.f)return this.f;var t=document.querySelector('link[rel="manifest"]');return this.f=t?fetch(t.href).then(function(e){return e.json()}).catch(function(){return Promise.resolve()}).then(function(t){if(t&&t.gcm_sender_id&&"103953800507"!==t.gcm_sender_id)throw e.e.create(u.codes.INCORRECT_GCM_SENDER_ID)}):Promise.resolve(),this.f},t.prototype.requestPermission=function(){var e=this;return"granted"===Notification.permission?Promise.resolve():new Promise(function(t,r){var n=function(n){return"granted"===n?t():r("denied"===n?e.e.create(u.codes.PERMISSION_BLOCKED):e.e.create(u.codes.PERMISSION_DEFAULT))},o=Notification.requestPermission(function(e){o||n(e)});o&&o.then(n)})},t.prototype.useServiceWorker=function(e){if(!(e instanceof ServiceWorkerRegistration))throw this.e.create(u.codes.SW_REGISTRATION_EXPECTED);if(void 0!==this.d)throw this.e.create(u.codes.USE_SW_BEFORE_GET_TOKEN);this.d=e},t.prototype.onMessage=function(e,t,r){return this.p(e,t,r)},t.prototype.onTokenRefresh=function(e,t,r){return this.g(e,t,r)},t.prototype.v=function(e){var t=this,r=e.installing||e.waiting||e.active;return new Promise(function(n,o){if(!r)return void o(t.e.create(u.codes.NO_SW_IN_REG));if("activated"===r.state)return void n(e);if("redundant"===r.state)return void o(t.e.create(u.codes.SW_REG_REDUNDANT));var i=function(){if("activated"===r.state)n(e);else{if("redundant"!==r.state)return;o(t.e.create(u.codes.SW_REG_REDUNDANT))}r.removeEventListener("statechange",i)};r.addEventListener("statechange",i)})},t.prototype._=function(){var e=this;return this.d?this.v(this.d):(this.d=null,navigator.serviceWorker.register(y.path,{scope:y.scope}).catch(function(t){throw e.e.create(u.codes.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:t.message})}).then(function(t){return e.v(t).then(function(){return e.d=t,t.update(),t})}))},t.prototype.T=function(){var e=this;"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",function(t){if(t.data&&t.data[m.PARAMS.TYPE_OF_MSG]){var r=t.data;switch(r[m.PARAMS.TYPE_OF_MSG]){case m.TYPES_OF_MSG.PUSH_MSG_RECEIVED:case m.TYPES_OF_MSG.NOTIFICATION_CLICKED:var n=r[m.PARAMS.DATA];e.h.next(n)}}},!1)},t.prototype.S=function(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")},t}(S),k=w,O=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),D=function(e){function t(t){var r=e.call(this,t)||this;return self.addEventListener("push",function(e){return r.I(e)},!1),self.addEventListener("pushsubscriptionchange",function(e){return r.m(e)},!1),self.addEventListener("notificationclick",function(e){return r.y(e)},!1),r.N=null,r}return O(t,e),t.prototype.I=function(e){var t,r=this;try{t=e.data.json()}catch(e){return}var n=this.w().then(function(e){if(e){if(t.notification||r.N)return r.k(t)}else{var n=r.O(t);if(n){var o=n.title||"";return self.registration.showNotification(o,n)}if(r.N)return r.N(t)}});e.waitUntil(n)},t.prototype.m=function(e){var t=this,r=this.getToken().then(function(e){if(!e)throw t.e.create(u.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);var r=null,n=t.getTokenManager();return n.getTokenDetailsFromToken(e).then(function(e){if(!(r=e))throw t.e.create(u.codes.INVALID_SAVED_TOKEN);return self.registration.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(e){return n.subscribeToFCM(r.fcmSenderId,e,r.fcmPushSet)}).catch(function(e){return n.deleteToken(r.fcmToken).then(function(){throw t.e.create(u.codes.UNABLE_TO_RESUBSCRIBE,{message:e})})})});e.waitUntil(r)},t.prototype.y=function(e){var t=this;if(e.notification&&e.notification.data&&e.notification.data.FCM_MSG){e.stopImmediatePropagation(),e.notification.close();var r=e.notification.data.FCM_MSG,n=r.notification.click_action;if(n){var o=this.D(n).then(function(e){return e||self.clients.openWindow(n)}).then(function(e){if(e){r.notification,delete r.notification;var n=m.createNewMsg(m.TYPES_OF_MSG.NOTIFICATION_CLICKED,r);return t.A(e,n)}});e.waitUntil(o)}}},t.prototype.O=function(e){if(e&&"object"==typeof e.notification){var t=Object.assign({},e.notification);return t.data=(r={},r.FCM_MSG=e,r),t;var r}},t.prototype.setBackgroundMessageHandler=function(e){if(e&&"function"!=typeof e)throw this.e.create(u.codes.BG_HANDLER_FUNCTION_EXPECTED);this.N=e},t.prototype.D=function(e){var t=new URL(e).href;return self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(function(e){for(var r=null,n=0;n} The IndexedDB database\n */\n TokenManager.prototype.openDatabase_ = function () {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(TokenManager.DB_NAME, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n TokenManager.prototype.closeDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenManager.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getTokenDetailsFromSWScope_ = function (swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getAllTokenDetailsForSenderId_ = function (senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n }\n else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n };\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n TokenManager.prototype.subscribeToFCM = function (senderId, subscription, pushSet) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (pushSet) {\n fcmSubscribeBody += \"&pushSet=\" + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n TokenManager.prototype.isSameSubscription_ = function (subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (subscription.endpoint === masterTokenDetails['endpoint'] &&\n array_buffer_to_base64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n array_buffer_to_base64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']);\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n TokenManager.prototype.saveTokenDetails_ = function (senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: array_buffer_to_base64(subscription['getKey']('auth')),\n p256dh: array_buffer_to_base64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n TokenManager.prototype.getSavedToken = function (senderId, swRegistration) {\n var _this = this;\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return (swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']);\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n })\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager\n .getSubscription()\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.GET_SUBSCRIPTION_FAILED);\n })\n .then(function (subscription) {\n if (subscription &&\n _this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n };\n /**\n * Creates a new FCM token.\n */\n TokenManager.prototype.createToken = function (senderId, swRegistration) {\n var _this = this;\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager\n .getSubscription()\n .then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n })\n .then(function (sub) {\n subscription = sub;\n return _this.subscribeToFCM(senderId, subscription);\n })\n .then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n })\n .then(function () { return fcmTokenDetails['token']; });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenManager.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenManager;\n}());\n/* harmony default export */ var token_manager = (token_manager_TokenManager);\n\n//# sourceMappingURL=token-manager.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/notification-permission.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var notification_permission = ({\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n});\n\n//# sourceMappingURL=notification-permission.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/controller-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\nvar controller_interface_ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new token_manager();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete; };\n }\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== notification_permission.granted) {\n if (currentPermission === notification_permission.denied) {\n return Promise.reject(this.errorFactory_.create(errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this.tokenManager_\n .getSavedToken(_this.messagingSenderId_, registration)\n .then(function (token) {\n if (token) {\n return token;\n }\n return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);\n });\n });\n };\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return this.tokenManager_.closeDatabase();\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n /**\n * @protected\n * @returns {TokenManager}\n */\n ControllerInterface.prototype.getTokenManager = function () {\n return this.tokenManager_;\n };\n return ControllerInterface;\n}());\n/* harmony default export */ var controller_interface = (controller_interface_ControllerInterface);\n\n//# sourceMappingURL=controller-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/worker-page-message.js\n/**\n * Copyright 2017 Google Inc.\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// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\n/* harmony default export */ var worker_page_message = ({\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n});\n\n//# sourceMappingURL=worker-page-message.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/default-sw.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var default_sw = ({\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n});\n\n//# sourceMappingURL=default-sw.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/window-controller.js\n/**\n * Copyright 2017 Google Inc.\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\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\n\nvar window_controller_WindowController = /** @class */ (function (_super) {\n __extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n var _this = this;\n if (Notification.permission === notification_permission.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === notification_permission.granted) {\n return resolve();\n }\n else if (result === notification_permission.denied) {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(default_sw.path, {\n scope: default_sw.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n case worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[worker_page_message.PARAMS.DATA];\n _this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(controller_interface));\n/* harmony default export */ var window_controller = (window_controller_WindowController);\n\n//# sourceMappingURL=window-controller.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/sw-controller.js\n/**\n * Copyright 2017 Google Inc.\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\nvar sw_controller___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\nvar FCM_MSG = 'FCM_MSG';\nvar sw_controller_SWController = /** @class */ (function (_super) {\n sw_controller___extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this.errorFactory_.create(errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this.getTokenManager();\n return tokenManager\n .getTokenDetailsFromToken(token)\n .then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this.errorFactory_.create(errors.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n })\n .then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this.errorFactory_.create(errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this.errorFactory_.create(errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n return SWController;\n}(controller_interface));\n/* harmony default export */ var sw_controller = (sw_controller_SWController);\n\n//# sourceMappingURL=sw-controller.js.map\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(6);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerMessaging\"] = registerMessaging;\n/**\n * Copyright 2017 Google Inc.\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\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new sw_controller(app);\n }\n // Assume we are in the window context.\n return new window_controller(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: window_controller\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[116]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/messaging');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./messaging/index.js\n// module id = 116\n// module chunks = 3","/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\nexport default function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n};\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport WindowController from './src/controllers/window-controller';\nimport SWController from './src/controllers/sw-controller';\nimport firebase from '@firebase/app';\nexport function registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n // Assume we are in the window context.\n return new WindowController(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: WindowController\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\nvar ERROR_MAP = (_a = {},\n _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key must be a string with at ' + 'least one character.',\n _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n _a);\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\nvar _a;\n\n//# sourceMappingURL=errors.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/errors.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar FCM_APPLICATION_SERVER_KEY = [\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n];\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\nexport default {\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n};\n\n//# sourceMappingURL=fcm-details.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/fcm-details.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar FCM_TOKEN_DETAILS_DB_VERSION = 1;\nvar TokenManager = /** @class */ (function () {\n function TokenManager() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.openDbPromise_ = null;\n }\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n TokenManager.prototype.openDatabase_ = function () {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(TokenManager.DB_NAME, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n TokenManager.prototype.closeDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenManager.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getTokenDetailsFromSWScope_ = function (swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getAllTokenDetailsForSenderId_ = function (senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n }\n else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n };\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n TokenManager.prototype.subscribeToFCM = function (senderId, subscription, pushSet) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (pushSet) {\n fcmSubscribeBody += \"&pushSet=\" + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n TokenManager.prototype.isSameSubscription_ = function (subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (subscription.endpoint === masterTokenDetails['endpoint'] &&\n arrayBufferToBase64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n arrayBufferToBase64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']);\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n TokenManager.prototype.saveTokenDetails_ = function (senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: arrayBufferToBase64(subscription['getKey']('auth')),\n p256dh: arrayBufferToBase64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n TokenManager.prototype.getSavedToken = function (senderId, swRegistration) {\n var _this = this;\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return (swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']);\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n })\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager\n .getSubscription()\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.GET_SUBSCRIPTION_FAILED);\n })\n .then(function (subscription) {\n if (subscription &&\n _this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n };\n /**\n * Creates a new FCM token.\n */\n TokenManager.prototype.createToken = function (senderId, swRegistration) {\n var _this = this;\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager\n .getSubscription()\n .then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(function (sub) {\n subscription = sub;\n return _this.subscribeToFCM(senderId, subscription);\n })\n .then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n })\n .then(function () { return fcmTokenDetails['token']; });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenManager.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenManager;\n}());\nexport default TokenManager;\n\n//# sourceMappingURL=token-manager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/token-manager.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenManager from '../models/token-manager';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\nvar ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new TokenManager();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete; };\n }\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this.tokenManager_\n .getSavedToken(_this.messagingSenderId_, registration)\n .then(function (token) {\n if (token) {\n return token;\n }\n return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);\n });\n });\n };\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return this.tokenManager_.closeDatabase();\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n /**\n * @protected\n * @returns {TokenManager}\n */\n ControllerInterface.prototype.getTokenManager = function () {\n return this.tokenManager_;\n };\n return ControllerInterface;\n}());\nexport default ControllerInterface;\n\n//# sourceMappingURL=controller-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/controller-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\nexport default {\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n};\n\n//# sourceMappingURL=worker-page-message.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/worker-page-message.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n//# sourceMappingURL=default-sw.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/default-sw.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport { createSubscribe } from '@firebase/util';\nvar WindowController = /** @class */ (function (_super) {\n __extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(Errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n var _this = this;\n if (Notification.permission === NOTIFICATION_PERMISSION.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n }\n else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n _this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(ControllerInterface));\nexport default WindowController;\n\n//# sourceMappingURL=window-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/window-controller.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport FCMDetails from '../models/fcm-details';\nvar FCM_MSG = 'FCM_MSG';\nvar SWController = /** @class */ (function (_super) {\n __extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this.errorFactory_.create(Errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this.getTokenManager();\n return tokenManager\n .getTokenDetailsFromToken(token)\n .then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this.errorFactory_.create(Errors.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this.errorFactory_.create(Errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(Errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this.errorFactory_.create(Errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n return SWController;\n}(ControllerInterface));\nexport default SWController;\n\n//# sourceMappingURL=sw-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/sw-controller.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///firebase-messaging.js","webpack:///./messaging/index.js","webpack:///../messaging/dist/esm/src/helpers/array-buffer-to-base64.js","webpack:///../messaging/dist/esm/src/models/clean-v1-undefined.js","webpack:///../messaging/dist/esm/src/models/token-details-model.js","webpack:///../messaging/dist/esm/index.js","webpack:///../messaging/dist/esm/src/models/errors.js","webpack:///../messaging/dist/esm/src/models/db-interface.js","webpack:///../messaging/dist/esm/src/models/fcm-details.js","webpack:///../messaging/dist/esm/src/models/iid-model.js","webpack:///../messaging/dist/esm/src/models/vapid-details-model.js","webpack:///../messaging/dist/esm/src/controllers/controller-interface.js","webpack:///../messaging/dist/esm/src/models/worker-page-message.js","webpack:///../messaging/dist/esm/src/models/default-sw.js","webpack:///../messaging/dist/esm/src/helpers/base64-to-array-buffer.js","webpack:///../messaging/dist/esm/src/controllers/window-controller.js","webpack:///../messaging/dist/esm/src/controllers/sw-controller.js"],"names":["webpackJsonpFirebase","120","module","exports","__webpack_require__","121","__webpack_exports__","toBase64","arrayBuffer","uint8Version","Uint8Array","window","btoa","String","fromCharCode","apply","handleDb","db","objectStoreNames","contains","OLD_OBJECT_STORE_NAME","transaction","objectStore","iidModel","iid_model","openCursorRequest","openCursor","onerror","event","console","warn","onsuccess","cursor","result","tokenDetails","value","deleteToken","fcmSenderId","fcmToken","fcmPushSet","continue","close","indexedDB","deleteDatabase","OLD_DB_NAME","cleanV1","request","open","ValidateInput","registerMessaging","instance","factoryMethod","app","self","sw_controller","window_controller","namespaceExports","Messaging","INTERNAL","registerService","Object","defineProperty","errors__a","tslib_es6","cjs","CODES","AVAILABLE_IN_WINDOW","AVAILABLE_IN_SW","SHOULD_BE_INHERITED","BAD_SENDER_ID","INCORRECT_GCM_SENDER_ID","PERMISSION_DEFAULT","PERMISSION_BLOCKED","UNSUPPORTED_BROWSER","NOTIFICATIONS_BLOCKED","FAILED_DEFAULT_REGISTRATION","SW_REGISTRATION_EXPECTED","GET_SUBSCRIPTION_FAILED","INVALID_SAVED_TOKEN","SW_REG_REDUNDANT","TOKEN_SUBSCRIBE_FAILED","TOKEN_SUBSCRIBE_NO_TOKEN","TOKEN_SUBSCRIBE_NO_PUSH_SET","TOKEN_UNSUBSCRIBE_FAILED","TOKEN_UPDATE_FAILED","TOKEN_UPDATE_NO_TOKEN","USE_SW_BEFORE_GET_TOKEN","INVALID_DELETE_TOKEN","DELETE_TOKEN_NOT_FOUND","DELETE_SCOPE_NOT_FOUND","BG_HANDLER_FUNCTION_EXPECTED","NO_WINDOW_CLIENT_TO_MSG","UNABLE_TO_RESUBSCRIBE","NO_FCM_TOKEN_FOR_RESUBSCRIBE","FAILED_TO_DELETE_TOKEN","NO_SW_IN_REG","BAD_SCOPE","BAD_VAPID_KEY","BAD_SUBSCRIPTION","BAD_TOKEN","BAD_PUSH_SET","FAILED_DELETE_VAPID_KEY","INVALID_PUBLIC_VAPID_KEY","USE_PUBLIC_KEY_BEFORE_GET_TOKEN","PUBLIC_KEY_DECRYPTION_FAILED","ERROR_MAP","errors","codes","map","db_interface_DBInterface","DBInterface","dbName","dbVersion","this","errorFactory_","DB_NAME_","dbVersion_","openDbPromise_","TRANSACTION_READ_WRITE","prototype","openDatabase","_this","Promise","resolve","reject","target","error","onupgradeneeded","onDBUpgrade","err","closeDatabase","then","create","db_interface","array_buffer_to_base64","replace","DEFAULT_PUBLIC_VAPID_KEY","SUBSCRIPTION_DETAILS","userVisibleOnly","applicationServerKey","fcm_details","ENDPOINT","iid_model_IIDModel","IIDModel","getToken","senderId","subscription","publicVapidKey","p256dh","auth","fcmSubscribeBody","endpoint","headers","Headers","append","subscribeOptions","method","body","fetch","response","json","catch","fcmTokenResponse","message","token","pushSet","updateToken","fcmUpdateBody","updateFetchRes","updateOptions","fetchResponse","ok","fcmUnsubscribeBody","unsubscribeOptions","DB_NAME","DB_VERSION","swScope","vapidKey","token_details_model_TokenDetailsModel","_super","TokenDetailsModel","call","evt","oldVersion","createObjectStore","keyPath","createIndex","unique","validateInputs_","input","_a","length","PushSubscription","getTokenDetailsFromToken","index","get","getTokenDetailsFromSWScope","scopeRequest","saveTokenDetails","details","createTime","Date","now","put","delete","token_details_model","vapid_details_model_DB_NAME","vapid_details_model_DB_VERSION","vapid_details_model_VapidDetailsModel","VapidDetailsModel","getVapidFromSWScope","saveVapidDetails","deleteVapidDetails","vapid_details_model","SENDER_ID_OPTION_NAME","controller_interface_ControllerInterface","ControllerInterface","options","messagingSenderId_","tokenDetailsModel_","vapidDetailsModel_","iidModel_","currentPermission","getNotificationPermission_","notification_permission","swReg","getSWRegistration_","reg","scope","manageExistingToken","getNewToken","isTokenStillValid","isValid","getPublicVapidKey_","publicKey","updatedToken","getPushSubscription_","pushSubscription","allDetails","iidTokenDetails","registration","pushManager","getSubscription","unsubscribe","requestPermission","useServiceWorker","usePublicVapidKey","b64PublicKey","onMessage","nextOrObserver","optError","optCompleted","onTokenRefresh","setBackgroundMessageHandler","callback","all","Notification","permission","getTokenDetailsModel","getVapidDetailsModel","getIIDModel","controller_interface","PARAMS","TYPE_OF_MSG","DATA","msgType","PUSH_MSG_RECEIVED","NOTIFICATION_CLICKED","createNewMsg","msgData","worker_page_message","TYPES_OF_MSG","default_sw","path","base64_to_array_buffer","base64String","padding","repeat","base64","rawData","atob","outputArray","i","charCodeAt","window_controller_WindowController","WindowController","messageObserver_","onMessage_","observer","tokenRefreshObserver_","onTokenRefresh_","registrationToUse_","manifestCheckPromise_","setupSWMessageListener_","isSupported_","manifestCheck_","manifestTag","document","querySelector","href","manifestContent","managePermissionResult","permissionPromise","ServiceWorkerRegistration","publicVapidKeyToUse_","parsedKey","waitForRegistrationToActivate_","serviceWorker","installing","waiting","active","state","stateChangeListener","removeEventListener","addEventListener","navigator","register","browserErrorMessage","update","swRegistration","subscribe","data","workerPageMessage","pushMessage","next","hasOwnProperty","sw_controller_SWController","SWController","e","onPush_","onSubChange_","onNotificationClick_","bgMessageHandler_","msgPayload","handleMsgPromise","hasVisibleClients_","hasVisibleClients","notification","sendMessageToWindowClients_","notificationDetails","getNotificationData_","notificationTitle_1","title","showNotification","waitUntil","promiseChain","stopImmediatePropagation","clickAction","getWindowClient_","windowClient","focus","clients","openWindow","internalMsg","attemptToMessageClient_","notificationInformation","assign","url","parsedURL","URL","location","matchAll","type","includeUncontrolled","clientList","suitableClient","client","postMessage","some","visibilityState","vapidKeyFromDatabase","esm","Error"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IAExBC,IACA,SAAUC,EAAQC,EAASC,GCOjCA,EAAA,MDgBMC,IACA,SAAUH,EAAQI,EAAqBF,GAE7C,YEpBA,SAAAG,GAAAC,GACA,GAAAC,GAAA,GAAAC,YAAAF,EACA,OAAAG,QAAAC,KAAAC,OAAAC,aAAAC,MAAA,KAAAN,ICYA,QAAAO,GAAAC,GACA,GAAAA,EAAAC,iBAAAC,SAAAC,GAAA,CAKA,GAAAC,GAAAJ,EAAAI,YAAAD,GACAE,EAAAD,EAAAC,YAAAF,GACAG,EAAA,GAAAC,GACAC,E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LqqEG,MACO,MAAMrP,GACN,KAAUsP,OACR","file":"firebase-messaging.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([3],{\n\n/***/ 120:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(121);\n\n\n/***/ }),\n\n/***/ 121:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: /tmp/tmp-208812ou3wR5n5ZCvd/node_modules/tslib/tslib.es6.js\nvar tslib_es6 = __webpack_require__(2);\n\n// EXTERNAL MODULE: ../util/dist/cjs/index.js\nvar cjs = __webpack_require__(0);\nvar cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/errors.js\n/**\n * Copyright 2017 Google Inc.\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\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED: 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\n};\nvar ERROR_MAP = (errors__a = {},\n errors__a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n errors__a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n errors__a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n errors__a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n errors__a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n errors__a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n errors__a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n errors__a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n errors__a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n errors__a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n errors__a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n errors__a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n errors__a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n errors__a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n errors__a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n errors__a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n errors__a[CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}',\n errors__a[CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}',\n errors__a[CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.',\n errors__a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n errors__a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n errors__a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n errors__a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n errors__a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n errors__a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n errors__a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n errors__a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n errors__a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n errors__a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n errors__a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n errors__a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n errors__a[CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.',\n errors__a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n errors__a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n errors__a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n errors__a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n errors__a[CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.',\n errors__a[CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.',\n errors__a);\n/* harmony default export */ var errors = ({\n codes: CODES,\n map: ERROR_MAP\n});\nvar errors__a;\n\n//# sourceMappingURL=errors.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/db-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar db_interface_DBInterface = /** @class */ (function () {\n /**\n * @param {string} dbName\n * @param {number} dbVersion\n */\n function DBInterface(dbName, dbVersion) {\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n this.DB_NAME_ = dbName;\n this.dbVersion_ = dbVersion;\n this.openDbPromise_ = null;\n this.TRANSACTION_READ_WRITE = 'readwrite';\n }\n /**\n * Get the indexedDB as a promsie.\n * @protected\n * @return {!Promise} The IndexedDB database\n */\n DBInterface.prototype.openDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(_this.DB_NAME_, _this.dbVersion_);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n try {\n var db = event.target.result;\n _this.onDBUpgrade(db, event);\n }\n catch (err) {\n // close the database as it can't be used.\n db.close();\n reject(err);\n }\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {!Promise} Returns the result of the promise chain.\n */\n DBInterface.prototype.closeDatabase = function () {\n var _this = this;\n return Promise.resolve().then(function () {\n if (_this.openDbPromise_) {\n return _this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n });\n };\n /**\n * @protected\n * @param {!IDBDatabase} db\n */\n DBInterface.prototype.onDBUpgrade = function (db, event) {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n return DBInterface;\n}());\n/* harmony default export */ var db_interface = (db_interface_DBInterface);\n\n//# sourceMappingURL=db-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n/* harmony default export */ var array_buffer_to_base64 = (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n});\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/fcm-details.js\n/**\n * Copyright 2017 Google Inc.\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\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n]);\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: DEFAULT_PUBLIC_VAPID_KEY\n};\n/* harmony default export */ var fcm_details = ({\n DEFAULT_PUBLIC_VAPID_KEY: DEFAULT_PUBLIC_VAPID_KEY,\n SUBSCRIPTION_DETAILS: SUBSCRIPTION_DETAILS,\n ENDPOINT: 'https://fcm.googleapis.com'\n // ENDPOINT: 'https://jmt17.google.com'\n});\n\n//# sourceMappingURL=fcm-details.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/iid-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar iid_model_IIDModel = /** @class */ (function () {\n function IIDModel() {\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n }\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {Uint8Array} publicVapidKey The public VAPID key.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n IIDModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== fcm_details.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = array_buffer_to_base64(publicVapidKey);\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .catch(function () {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED);\n })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Update the underlying token details for fcmToken.\n */\n IIDModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"authorized_entity=\" + senderId + \"&\") +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== fcm_details.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = array_buffer_to_base64(publicVapidKey);\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var updateOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUpdateBody\n };\n var updateFetchRes;\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', updateOptions)\n .then(function (fetchResponse) {\n updateFetchRes = fetchResponse;\n return fetchResponse.json();\n })\n .catch(function () {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_FAILED);\n })\n .then(function (fcmTokenResponse) {\n if (!updateFetchRes.ok) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_NO_TOKEN);\n }\n return fcmTokenResponse['token'];\n });\n };\n /**\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\n */\n IIDModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\n var _this = this;\n var fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"pushSet=\" + fcmPushSet);\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var unsubscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUnsubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions).then(function (fetchResponse) {\n if (!fetchResponse.ok) {\n return fetchResponse.json().then(function (fcmTokenResponse) {\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_UNSUBSCRIBE_FAILED, {\n message: message\n });\n }\n }, function (err) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UNSUBSCRIBE_FAILED);\n });\n }\n });\n };\n return IIDModel;\n}());\n/* harmony default export */ var iid_model = (iid_model_IIDModel);\n\n//# sourceMappingURL=iid-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/clean-v1-undefined.js\n/**\n * Copyright 2017 Google Inc.\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 * There seems to have been a bug in the messaging SDK versions <= 4.9.x\n * where the IndexedDB model was using a database name of 'undefined'.\n *\n * In 4.10.x we changed the model implementation, but kept the database\n * name as it should have been. This however introduced an issue where\n * two tokens were pointing to the same underlying PushSubscription.\n *\n * This code will look for the undefined database and delete any of the\n * underlying tokens.\n */\n\nvar OLD_DB_NAME = 'undefined';\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\nfunction handleDb(db) {\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // We found a database with the name 'undefined', but our expected object\n // store isn't defined.\n return;\n }\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\n var iidModel = new iid_model();\n var openCursorRequest = objectStore.openCursor();\n openCursorRequest.onerror = function (event) {\n // NOOP - Nothing we can do.\n console.warn('Unable to cleanup old IDB.', event);\n };\n openCursorRequest.onsuccess = function () {\n var cursor = openCursorRequest.result;\n if (cursor) {\n // cursor.value contains the current record being iterated through\n // this is where you'd do something with the result\n var tokenDetails = cursor.value;\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\n cursor.continue();\n }\n else {\n db.close();\n indexedDB.deleteDatabase(OLD_DB_NAME);\n }\n };\n}\nfunction cleanV1() {\n var request = indexedDB.open(OLD_DB_NAME);\n request.onerror = function (event) {\n // NOOP - Nothing we can do.\n };\n request.onsuccess = function (event) {\n var db = request.result;\n handleDb(db);\n };\n}\n\n\n//# sourceMappingURL=clean-v1-undefined.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/token-details-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar DB_NAME = 'fcm_token_details_db';\nvar DB_VERSION = 2;\n/** @record */\nfunction ValidateInput() { }\n/** @type {string|undefined} */\nValidateInput.prototype.fcmToken;\n/** @type {string|undefined} */\nValidateInput.prototype.swScope;\n/** @type {string|undefined} */\nValidateInput.prototype.vapidKey;\n/** @type {PushSubscription|undefined} */\nValidateInput.prototype.subscription;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmSenderId;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmPushSet;\nvar token_details_model_TokenDetailsModel = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](TokenDetailsModel, _super);\n function TokenDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n TokenDetailsModel.prototype.onDBUpgrade = function (db, evt) {\n if (evt.oldVersion < 1) {\n // New IDB instance\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n }\n if (evt.oldVersion < 2) {\n // Prior to version 2, we were using either 'fcm_token_details_db'\n // or 'undefined' as the database name due to bug in the SDK\n // So remove the old tokens and databases.\n cleanV1();\n }\n };\n /**\n * This method takes an object and will check for known arguments and\n * validate the input.\n * @private\n * @param {!ValidateInput} input\n * @return {!Promise} Returns promise that resolves if input is valid,\n * rejects otherwise.\n */\n TokenDetailsModel.prototype.validateInputs_ = function (input) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (input.fcmToken) {\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN))];\n }\n }\n if (input.swScope) {\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE))];\n }\n }\n if (input.vapidKey) {\n if (!(input.vapidKey instanceof Uint8Array) ||\n input.vapidKey.length !== 65) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY))];\n }\n }\n if (input.subscription) {\n if (!(input.subscription instanceof PushSubscription)) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SUBSCRIPTION))];\n }\n }\n if (input.fcmSenderId) {\n if (typeof input.fcmSenderId !== 'string' ||\n input.fcmSenderId.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID))];\n }\n }\n if (input.fcmPushSet) {\n if (typeof input.fcmPushSet !== 'string' ||\n input.fcmPushSet.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_PUSH_SET))];\n }\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\n var _this = this;\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN));\n }\n return this.validateInputs_({ fcmToken: fcmToken })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Given a service worker scope, this method will look up the details in\n * indexedDB.\n * @public\n * @param {string} swScope\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\n var _this = this;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n return this.validateInputs_({ swScope: swScope })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @param {{swScope: !string, vapidKey: !string,\n * subscription: !PushSubscription, fcmSenderId: !string, fcmToken: !string,\n * fcmPushSet: !string}} input A plain js object containing args to save.\n * @return {Promise}\n */\n TokenDetailsModel.prototype.saveTokenDetails = function (_a) {\n var _this = this;\n var swScope = _a.swScope, vapidKey = _a.vapidKey, subscription = _a.subscription, fcmSenderId = _a.fcmSenderId, fcmToken = _a.fcmToken, fcmPushSet = _a.fcmPushSet;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n if (!vapidKey) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY));\n }\n if (!subscription) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SUBSCRIPTION));\n }\n if (!fcmSenderId) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN));\n }\n if (!fcmPushSet) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_PUSH_SET));\n }\n return this.validateInputs_({\n swScope: swScope,\n vapidKey: vapidKey,\n subscription: subscription,\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet\n })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n /**\n * @dict\n */\n var details = {\n swScope: swScope,\n vapidKey: array_buffer_to_base64(vapidKey),\n endpoint: subscription.endpoint,\n auth: array_buffer_to_base64(subscription['getKey']('auth')),\n p256dh: array_buffer_to_base64(subscription['getKey']('p256dh')),\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n createTime: Date.now()\n };\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenDetailsModel.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenDetailsModel;\n}(db_interface));\n/* harmony default export */ var token_details_model = (token_details_model_TokenDetailsModel);\n\n//# sourceMappingURL=token-details-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/vapid-details-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar FCM_VAPID_OBJ_STORE = 'fcm_vapid_object_Store';\nvar vapid_details_model_DB_NAME = 'fcm_vapid_details_db';\nvar vapid_details_model_DB_VERSION = 1;\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\nvar vapid_details_model_VapidDetailsModel = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](VapidDetailsModel, _super);\n function VapidDetailsModel() {\n return _super.call(this, vapid_details_model_DB_NAME, vapid_details_model_DB_VERSION) || this;\n }\n /**\n * @override\n * @param {IDBDatabase} db\n */\n VapidDetailsModel.prototype.onDBUpgrade = function (db) {\n db.createObjectStore(FCM_VAPID_OBJ_STORE, {\n keyPath: 'swScope'\n });\n };\n /**\n * Given a service worker scope, this method will look up the vapid key\n * in indexedDB.\n */\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function () {\n reject(scopeRequest.error);\n };\n scopeRequest.onsuccess = function () {\n var result = scopeRequest.result;\n var vapidKey = null;\n if (result) {\n vapidKey = result.vapidKey;\n }\n resolve(vapidKey);\n };\n });\n });\n };\n /**\n * Save a vapid key against a swScope for later date.\n */\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\n var _this = this;\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY));\n }\n var details = {\n swScope: swScope,\n vapidKey: vapidKey\n };\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM VAPID key for a SW scope.\n * Resolves once the scope/vapid details have been deleted and returns the\n * deleted vapid key.\n */\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\n var _this = this;\n return this.getVapidFromSWScope(swScope).then(function (vapidKey) {\n if (!vapidKey) {\n throw _this.errorFactory_.create(errors.codes.DELETE_SCOPE_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.delete(swScope);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n if (request.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_DELETE_VAPID_KEY));\n return;\n }\n resolve(vapidKey);\n };\n });\n });\n });\n };\n return VapidDetailsModel;\n}(db_interface));\n/* harmony default export */ var vapid_details_model = (vapid_details_model_VapidDetailsModel);\n\n//# sourceMappingURL=vapid-details-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/notification-permission.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var notification_permission = ({\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n});\n\n//# sourceMappingURL=notification-permission.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/controller-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nvar TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\nvar controller_interface_ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenDetailsModel_ = new token_details_model();\n this.vapidDetailsModel_ = new vapid_details_model();\n this.iidModel_ = new iid_model();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete(); };\n }\n /**\n * @export\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== notification_permission.granted) {\n if (currentPermission === notification_permission.denied) {\n return Promise.reject(this.errorFactory_.create(errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n var swReg;\n return this.getSWRegistration_()\n .then(function (reg) {\n swReg = reg;\n return _this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(function (tokenDetails) {\n if (tokenDetails) {\n return _this.manageExistingToken(tokenDetails, swReg);\n }\n return _this.getNewToken(swReg);\n });\n };\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n ControllerInterface.prototype.manageExistingToken = function (tokenDetails, swReg) {\n var _this = this;\n return this.isTokenStillValid(tokenDetails).then(function (isValid) {\n if (isValid) {\n var now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n }\n else {\n return _this.updateToken(tokenDetails, swReg);\n }\n }\n else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n return _this.getNewToken(swReg);\n });\n }\n });\n };\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n ControllerInterface.prototype.isTokenStillValid = function (tokenDetails) {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(function (publicKey) {\n if (array_buffer_to_base64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n };\n ControllerInterface.prototype.updateToken = function (tokenDetails, swReg) {\n var _this = this;\n var publicVapidKey;\n var updatedToken;\n var subscription;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.updateToken(_this.messagingSenderId_, tokenDetails['fcmToken'], tokenDetails['fcmPushSet'], subscription, publicVapidKey);\n })\n .catch(function (err) {\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n })\n .then(function (token) {\n updatedToken = token;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return updatedToken;\n });\n };\n ControllerInterface.prototype.getNewToken = function (swReg) {\n var _this = this;\n var publicVapidKey;\n var subscription;\n var tokenDetails;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.getToken(_this.messagingSenderId_, subscription, publicVapidKey);\n })\n .then(function (iidTokenDetails) {\n tokenDetails = iidTokenDetails;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return tokenDetails['token'];\n });\n };\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(function (details) {\n return _this.iidModel_.deleteToken(details['fcmSenderId'], details['fcmToken'], details['fcmPushSet']);\n })\n .then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n ControllerInterface.prototype.getPublicVapidKey_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!string} b64PublicKey\n */\n ControllerInterface.prototype.usePublicVapidKey = function (b64PublicKey) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n ControllerInterface.prototype.getTokenDetailsModel = function () {\n return this.tokenDetailsModel_;\n };\n ControllerInterface.prototype.getVapidDetailsModel = function () {\n return this.vapidDetailsModel_;\n };\n /**\n * @protected\n * @returns {IIDModel}\n */\n ControllerInterface.prototype.getIIDModel = function () {\n return this.iidModel_;\n };\n return ControllerInterface;\n}());\n/* harmony default export */ var controller_interface = (controller_interface_ControllerInterface);\n\n//# sourceMappingURL=controller-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/worker-page-message.js\n/**\n * Copyright 2017 Google Inc.\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// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\n/* harmony default export */ var worker_page_message = ({\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n});\n\n//# sourceMappingURL=worker-page-message.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/default-sw.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var default_sw = ({\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n});\n\n//# sourceMappingURL=default-sw.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/helpers/base64-to-array-buffer.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var base64_to_array_buffer = (function (base64String) {\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\n var base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n var rawData = window.atob(base64);\n var outputArray = new Uint8Array(rawData.length);\n for (var i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n});\n\n//# sourceMappingURL=base64-to-array-buffer.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/window-controller.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\nvar window_controller_WindowController = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n _this.messageObserver_ = null;\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (Notification.permission === notification_permission.granted) {\n return [2 /*return*/];\n }\n return [2 /*return*/, new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === notification_permission.granted) {\n return resolve();\n }\n else if (result === notification_permission.denied) {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(managePermissionResult);\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n })];\n });\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\n }\n var parsedKey = base64_to_array_buffer(publicKey);\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(errors.codes.PUBLIC_KEY_DECRYPTION_FAILED);\n }\n this.publicVapidKeyToUse_ = parsedKey;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(default_sw.path, {\n scope: default_sw.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n WindowController.prototype.getPublicVapidKey_ = function () {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n return Promise.resolve(fcm_details.DEFAULT_PUBLIC_VAPID_KEY);\n };\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise}\n */\n WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n case worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[worker_page_message.PARAMS.DATA];\n if (_this.messageObserver_) {\n _this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(controller_interface));\n/* harmony default export */ var window_controller = (window_controller_WindowController);\n\n//# sourceMappingURL=window-controller.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/sw-controller.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar FCM_MSG = 'FCM_MSG';\nvar sw_controller_SWController = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle_1 = notificationDetails.title || '';\n return _this.getSWRegistration_().then(function (reg) {\n return reg.showNotification(notificationTitle_1, notificationDetails);\n });\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getSWRegistration_()\n .then(function (registration) {\n return registration.pushManager\n .getSubscription()\n .then(function (subscription) {\n // TODO: Check if it's still valid\n // TODO: If not, then update token\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n var tokenDetailsModel = _this.getTokenDetailsModel();\n return tokenDetailsModel\n .getTokenDetailsFromSWScope(registration.scope)\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n // This should rarely occure, but could if indexedDB\n // is corrupted or wiped\n throw err;\n }\n // Attempt to delete the token if we know it's bad\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n });\n });\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n if (!msgPayload['notification']) {\n // Nothing to do.\n return;\n }\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient.focus();\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (!callback || typeof callback !== 'function') {\n throw this.errorFactory_.create(errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url, self.location).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url, self.location).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n return suitableClient;\n }\n return null;\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // NOTE: This returns a promise in case this API is abstracted later on to\n // do additional work\n if (!client) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.NO_WINDOW_CLIENT_TO_MSG))];\n }\n client.postMessage(message);\n return [2 /*return*/];\n });\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n /**\n * This will return the default VAPID key or the uint8array version of the\n * public VAPID key provided by the developer.\n */\n SWController.prototype.getPublicVapidKey_ = function () {\n var _this = this;\n return this.getSWRegistration_()\n .then(function (swReg) {\n return _this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope);\n })\n .then(function (vapidKeyFromDatabase) {\n if (vapidKeyFromDatabase === null) {\n return fcm_details.DEFAULT_PUBLIC_VAPID_KEY;\n }\n return vapidKeyFromDatabase;\n });\n };\n return SWController;\n}(controller_interface));\n/* harmony default export */ var sw_controller = (sw_controller_SWController);\n\n//# sourceMappingURL=sw-controller.js.map\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerMessaging\"] = registerMessaging;\n/**\n * Copyright 2017 Google Inc.\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\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new sw_controller(app);\n }\n // Assume we are in the window context.\n return new window_controller(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: window_controller\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(esm[\"firebase\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[120]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/messaging');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./messaging/index.js\n// module id = 120\n// module chunks = 3","/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\nexport default (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n});\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * There seems to have been a bug in the messaging SDK versions <= 4.9.x\n * where the IndexedDB model was using a database name of 'undefined'.\n *\n * In 4.10.x we changed the model implementation, but kept the database\n * name as it should have been. This however introduced an issue where\n * two tokens were pointing to the same underlying PushSubscription.\n *\n * This code will look for the undefined database and delete any of the\n * underlying tokens.\n */\nimport IIDModel from '../models/iid-model';\nvar OLD_DB_NAME = 'undefined';\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\nfunction handleDb(db) {\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // We found a database with the name 'undefined', but our expected object\n // store isn't defined.\n return;\n }\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\n var iidModel = new IIDModel();\n var openCursorRequest = objectStore.openCursor();\n openCursorRequest.onerror = function (event) {\n // NOOP - Nothing we can do.\n console.warn('Unable to cleanup old IDB.', event);\n };\n openCursorRequest.onsuccess = function () {\n var cursor = openCursorRequest.result;\n if (cursor) {\n // cursor.value contains the current record being iterated through\n // this is where you'd do something with the result\n var tokenDetails = cursor.value;\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\n cursor.continue();\n }\n else {\n db.close();\n indexedDB.deleteDatabase(OLD_DB_NAME);\n }\n };\n}\nfunction cleanV1() {\n var request = indexedDB.open(OLD_DB_NAME);\n request.onerror = function (event) {\n // NOOP - Nothing we can do.\n };\n request.onsuccess = function (event) {\n var db = request.result;\n handleDb(db);\n };\n}\nexport { cleanV1 };\n\n//# sourceMappingURL=clean-v1-undefined.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/clean-v1-undefined.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport DBInterface from './db-interface';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport { cleanV1 } from './clean-v1-undefined';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar DB_NAME = 'fcm_token_details_db';\nvar DB_VERSION = 2;\n/** @record */\nfunction ValidateInput() { }\n/** @type {string|undefined} */\nValidateInput.prototype.fcmToken;\n/** @type {string|undefined} */\nValidateInput.prototype.swScope;\n/** @type {string|undefined} */\nValidateInput.prototype.vapidKey;\n/** @type {PushSubscription|undefined} */\nValidateInput.prototype.subscription;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmSenderId;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmPushSet;\nvar TokenDetailsModel = /** @class */ (function (_super) {\n tslib_1.__extends(TokenDetailsModel, _super);\n function TokenDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n TokenDetailsModel.prototype.onDBUpgrade = function (db, evt) {\n if (evt.oldVersion < 1) {\n // New IDB instance\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n }\n if (evt.oldVersion < 2) {\n // Prior to version 2, we were using either 'fcm_token_details_db'\n // or 'undefined' as the database name due to bug in the SDK\n // So remove the old tokens and databases.\n cleanV1();\n }\n };\n /**\n * This method takes an object and will check for known arguments and\n * validate the input.\n * @private\n * @param {!ValidateInput} input\n * @return {!Promise} Returns promise that resolves if input is valid,\n * rejects otherwise.\n */\n TokenDetailsModel.prototype.validateInputs_ = function (input) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (input.fcmToken) {\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN))];\n }\n }\n if (input.swScope) {\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE))];\n }\n }\n if (input.vapidKey) {\n if (!(input.vapidKey instanceof Uint8Array) ||\n input.vapidKey.length !== 65) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY))];\n }\n }\n if (input.subscription) {\n if (!(input.subscription instanceof PushSubscription)) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SUBSCRIPTION))];\n }\n }\n if (input.fcmSenderId) {\n if (typeof input.fcmSenderId !== 'string' ||\n input.fcmSenderId.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID))];\n }\n }\n if (input.fcmPushSet) {\n if (typeof input.fcmPushSet !== 'string' ||\n input.fcmPushSet.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_PUSH_SET))];\n }\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\n var _this = this;\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN));\n }\n return this.validateInputs_({ fcmToken: fcmToken })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Given a service worker scope, this method will look up the details in\n * indexedDB.\n * @public\n * @param {string} swScope\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\n var _this = this;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n return this.validateInputs_({ swScope: swScope })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @param {{swScope: !string, vapidKey: !string,\n * subscription: !PushSubscription, fcmSenderId: !string, fcmToken: !string,\n * fcmPushSet: !string}} input A plain js object containing args to save.\n * @return {Promise}\n */\n TokenDetailsModel.prototype.saveTokenDetails = function (_a) {\n var _this = this;\n var swScope = _a.swScope, vapidKey = _a.vapidKey, subscription = _a.subscription, fcmSenderId = _a.fcmSenderId, fcmToken = _a.fcmToken, fcmPushSet = _a.fcmPushSet;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n if (!vapidKey) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY));\n }\n if (!subscription) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SUBSCRIPTION));\n }\n if (!fcmSenderId) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN));\n }\n if (!fcmPushSet) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_PUSH_SET));\n }\n return this.validateInputs_({\n swScope: swScope,\n vapidKey: vapidKey,\n subscription: subscription,\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet\n })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n /**\n * @dict\n */\n var details = {\n swScope: swScope,\n vapidKey: arrayBufferToBase64(vapidKey),\n endpoint: subscription.endpoint,\n auth: arrayBufferToBase64(subscription['getKey']('auth')),\n p256dh: arrayBufferToBase64(subscription['getKey']('p256dh')),\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n createTime: Date.now()\n };\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenDetailsModel.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenDetailsModel;\n}(DBInterface));\nexport default TokenDetailsModel;\n\n//# sourceMappingURL=token-details-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/token-details-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport WindowController from './src/controllers/window-controller';\nimport SWController from './src/controllers/sw-controller';\nimport { firebase } from '@firebase/app';\nexport function registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n // Assume we are in the window context.\n return new WindowController(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: WindowController\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED: 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\n};\nvar ERROR_MAP = (_a = {},\n _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n _a[CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}',\n _a[CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}',\n _a[CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.',\n _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.',\n _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n _a[CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.',\n _a[CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.',\n _a);\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\nvar _a;\n\n//# sourceMappingURL=errors.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/errors.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nvar DBInterface = /** @class */ (function () {\n /**\n * @param {string} dbName\n * @param {number} dbVersion\n */\n function DBInterface(dbName, dbVersion) {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.DB_NAME_ = dbName;\n this.dbVersion_ = dbVersion;\n this.openDbPromise_ = null;\n this.TRANSACTION_READ_WRITE = 'readwrite';\n }\n /**\n * Get the indexedDB as a promsie.\n * @protected\n * @return {!Promise} The IndexedDB database\n */\n DBInterface.prototype.openDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(_this.DB_NAME_, _this.dbVersion_);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n try {\n var db = event.target.result;\n _this.onDBUpgrade(db, event);\n }\n catch (err) {\n // close the database as it can't be used.\n db.close();\n reject(err);\n }\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {!Promise} Returns the result of the promise chain.\n */\n DBInterface.prototype.closeDatabase = function () {\n var _this = this;\n return Promise.resolve().then(function () {\n if (_this.openDbPromise_) {\n return _this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n });\n };\n /**\n * @protected\n * @param {!IDBDatabase} db\n */\n DBInterface.prototype.onDBUpgrade = function (db, event) {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n return DBInterface;\n}());\nexport default DBInterface;\n\n//# sourceMappingURL=db-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/db-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n]);\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: DEFAULT_PUBLIC_VAPID_KEY\n};\nexport default {\n DEFAULT_PUBLIC_VAPID_KEY: DEFAULT_PUBLIC_VAPID_KEY,\n SUBSCRIPTION_DETAILS: SUBSCRIPTION_DETAILS,\n ENDPOINT: 'https://fcm.googleapis.com'\n // ENDPOINT: 'https://jmt17.google.com'\n};\n\n//# sourceMappingURL=fcm-details.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/fcm-details.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\nvar IIDModel = /** @class */ (function () {\n function IIDModel() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n }\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {Uint8Array} publicVapidKey The public VAPID key.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n IIDModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== FCMDetails.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .catch(function () {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED);\n })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Update the underlying token details for fcmToken.\n */\n IIDModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"authorized_entity=\" + senderId + \"&\") +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== FCMDetails.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var updateOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUpdateBody\n };\n var updateFetchRes;\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', updateOptions)\n .then(function (fetchResponse) {\n updateFetchRes = fetchResponse;\n return fetchResponse.json();\n })\n .catch(function () {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_FAILED);\n })\n .then(function (fcmTokenResponse) {\n if (!updateFetchRes.ok) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_NO_TOKEN);\n }\n return fcmTokenResponse['token'];\n });\n };\n /**\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\n */\n IIDModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\n var _this = this;\n var fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"pushSet=\" + fcmPushSet);\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var unsubscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUnsubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions).then(function (fetchResponse) {\n if (!fetchResponse.ok) {\n return fetchResponse.json().then(function (fcmTokenResponse) {\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UNSUBSCRIBE_FAILED, {\n message: message\n });\n }\n }, function (err) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UNSUBSCRIBE_FAILED);\n });\n }\n });\n };\n return IIDModel;\n}());\nexport default IIDModel;\n\n//# sourceMappingURL=iid-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/iid-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport DBInterface from './db-interface';\nimport Errors from './errors';\nvar FCM_VAPID_OBJ_STORE = 'fcm_vapid_object_Store';\nvar DB_NAME = 'fcm_vapid_details_db';\nvar DB_VERSION = 1;\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\nvar VapidDetailsModel = /** @class */ (function (_super) {\n tslib_1.__extends(VapidDetailsModel, _super);\n function VapidDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n /**\n * @override\n * @param {IDBDatabase} db\n */\n VapidDetailsModel.prototype.onDBUpgrade = function (db) {\n db.createObjectStore(FCM_VAPID_OBJ_STORE, {\n keyPath: 'swScope'\n });\n };\n /**\n * Given a service worker scope, this method will look up the vapid key\n * in indexedDB.\n */\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function () {\n reject(scopeRequest.error);\n };\n scopeRequest.onsuccess = function () {\n var result = scopeRequest.result;\n var vapidKey = null;\n if (result) {\n vapidKey = result.vapidKey;\n }\n resolve(vapidKey);\n };\n });\n });\n };\n /**\n * Save a vapid key against a swScope for later date.\n */\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\n var _this = this;\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY));\n }\n var details = {\n swScope: swScope,\n vapidKey: vapidKey\n };\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM VAPID key for a SW scope.\n * Resolves once the scope/vapid details have been deleted and returns the\n * deleted vapid key.\n */\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\n var _this = this;\n return this.getVapidFromSWScope(swScope).then(function (vapidKey) {\n if (!vapidKey) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_SCOPE_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.delete(swScope);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n if (request.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_DELETE_VAPID_KEY));\n return;\n }\n resolve(vapidKey);\n };\n });\n });\n });\n };\n return VapidDetailsModel;\n}(DBInterface));\nexport default VapidDetailsModel;\n\n//# sourceMappingURL=vapid-details-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/vapid-details-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport var TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\nvar ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete(); };\n }\n /**\n * @export\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n var swReg;\n return this.getSWRegistration_()\n .then(function (reg) {\n swReg = reg;\n return _this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(function (tokenDetails) {\n if (tokenDetails) {\n return _this.manageExistingToken(tokenDetails, swReg);\n }\n return _this.getNewToken(swReg);\n });\n };\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n ControllerInterface.prototype.manageExistingToken = function (tokenDetails, swReg) {\n var _this = this;\n return this.isTokenStillValid(tokenDetails).then(function (isValid) {\n if (isValid) {\n var now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n }\n else {\n return _this.updateToken(tokenDetails, swReg);\n }\n }\n else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n return _this.getNewToken(swReg);\n });\n }\n });\n };\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n ControllerInterface.prototype.isTokenStillValid = function (tokenDetails) {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(function (publicKey) {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n };\n ControllerInterface.prototype.updateToken = function (tokenDetails, swReg) {\n var _this = this;\n var publicVapidKey;\n var updatedToken;\n var subscription;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.updateToken(_this.messagingSenderId_, tokenDetails['fcmToken'], tokenDetails['fcmPushSet'], subscription, publicVapidKey);\n })\n .catch(function (err) {\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n })\n .then(function (token) {\n updatedToken = token;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return updatedToken;\n });\n };\n ControllerInterface.prototype.getNewToken = function (swReg) {\n var _this = this;\n var publicVapidKey;\n var subscription;\n var tokenDetails;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.getToken(_this.messagingSenderId_, subscription, publicVapidKey);\n })\n .then(function (iidTokenDetails) {\n tokenDetails = iidTokenDetails;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return tokenDetails['token'];\n });\n };\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(function (details) {\n return _this.iidModel_.deleteToken(details['fcmSenderId'], details['fcmToken'], details['fcmPushSet']);\n })\n .then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n ControllerInterface.prototype.getPublicVapidKey_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!string} b64PublicKey\n */\n ControllerInterface.prototype.usePublicVapidKey = function (b64PublicKey) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n ControllerInterface.prototype.getTokenDetailsModel = function () {\n return this.tokenDetailsModel_;\n };\n ControllerInterface.prototype.getVapidDetailsModel = function () {\n return this.vapidDetailsModel_;\n };\n /**\n * @protected\n * @returns {IIDModel}\n */\n ControllerInterface.prototype.getIIDModel = function () {\n return this.iidModel_;\n };\n return ControllerInterface;\n}());\nexport default ControllerInterface;\n\n//# sourceMappingURL=controller-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/controller-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\nexport default {\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n};\n\n//# sourceMappingURL=worker-page-message.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/worker-page-message.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n//# sourceMappingURL=default-sw.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/default-sw.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport default (function (base64String) {\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\n var base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n var rawData = window.atob(base64);\n var outputArray = new Uint8Array(rawData.length);\n for (var i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n});\n\n//# sourceMappingURL=base64-to-array-buffer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/base64-to-array-buffer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\nvar WindowController = /** @class */ (function (_super) {\n tslib_1.__extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n _this.messageObserver_ = null;\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(Errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib_1.__generator(this, function (_a) {\n if (Notification.permission === NOTIFICATION_PERMISSION.granted) {\n return [2 /*return*/];\n }\n return [2 /*return*/, new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n }\n else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(managePermissionResult);\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n })];\n });\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\n }\n var parsedKey = base64ToArrayBuffer(publicKey);\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED);\n }\n this.publicVapidKeyToUse_ = parsedKey;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n WindowController.prototype.getPublicVapidKey_ = function () {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\n };\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise}\n */\n WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (_this.messageObserver_) {\n _this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(ControllerInterface));\nexport default WindowController;\n\n//# sourceMappingURL=window-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/window-controller.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport FCMDetails from '../models/fcm-details';\nimport WorkerPageMessage from '../models/worker-page-message';\nvar FCM_MSG = 'FCM_MSG';\nvar SWController = /** @class */ (function (_super) {\n tslib_1.__extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle_1 = notificationDetails.title || '';\n return _this.getSWRegistration_().then(function (reg) {\n return reg.showNotification(notificationTitle_1, notificationDetails);\n });\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getSWRegistration_()\n .then(function (registration) {\n return registration.pushManager\n .getSubscription()\n .then(function (subscription) {\n // TODO: Check if it's still valid\n // TODO: If not, then update token\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n var tokenDetailsModel = _this.getTokenDetailsModel();\n return tokenDetailsModel\n .getTokenDetailsFromSWScope(registration.scope)\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n // This should rarely occure, but could if indexedDB\n // is corrupted or wiped\n throw err;\n }\n // Attempt to delete the token if we know it's bad\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n });\n });\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n if (!msgPayload['notification']) {\n // Nothing to do.\n return;\n }\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient.focus();\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (!callback || typeof callback !== 'function') {\n throw this.errorFactory_.create(Errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url, self.location).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url, self.location).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n return suitableClient;\n }\n return null;\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // NOTE: This returns a promise in case this API is abstracted later on to\n // do additional work\n if (!client) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.NO_WINDOW_CLIENT_TO_MSG))];\n }\n client.postMessage(message);\n return [2 /*return*/];\n });\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n /**\n * This will return the default VAPID key or the uint8array version of the\n * public VAPID key provided by the developer.\n */\n SWController.prototype.getPublicVapidKey_ = function () {\n var _this = this;\n return this.getSWRegistration_()\n .then(function (swReg) {\n return _this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope);\n })\n .then(function (vapidKeyFromDatabase) {\n if (vapidKeyFromDatabase === null) {\n return FCMDetails.DEFAULT_PUBLIC_VAPID_KEY;\n }\n return vapidKeyFromDatabase;\n });\n };\n return SWController;\n}(ControllerInterface));\nexport default SWController;\n\n//# sourceMappingURL=sw-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/sw-controller.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file diff --git a/lib/firebase/firebase-storage-externs.js b/lib/firebase/firebase-storage-externs.js index fceb0c5c..8087d6ec 100644 --- a/lib/firebase/firebase-storage-externs.js +++ b/lib/firebase/firebase-storage-externs.js @@ -1,5 +1,5 @@ /** - * Copyright 2017 Google Inc. + * @license Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/lib/firebase/firebase-storage.js b/lib/firebase/firebase-storage.js index e30a6153..34d7f579 100644 --- a/lib/firebase/firebase-storage.js +++ b/lib/firebase/firebase-storage.js @@ -1,7 +1,7 @@ /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -try{webpackJsonpFirebase([2],{118:function(t,e,n){n(119)},119:function(t,e,n){"use strict";function r(t){return"storage/"+t}function o(){return new te(ee.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function i(t){return new te(ee.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function a(t){return new te(ee.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function s(){return new te(ee.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}function u(t){return new te(ee.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function c(){return new te(ee.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function l(){return new te(ee.CANCELED,"User canceled the upload/download.")}function h(t){return new te(ee.INVALID_URL,"Invalid URL '"+t+"'.")}function p(t){return new te(ee.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function f(){return new te(ee.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function d(){return new te(ee.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function _(){return new te(ee.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function v(t,e,n){return new te(ee.INVALID_ARGUMENT,"Invalid argument in `"+e+"` at index "+t+": "+n)}function b(t,e,n,r){var o,i;return t===e?(o=t,i=1===t?"argument":"arguments"):(o="between "+t+" and "+e,i="arguments"),new te(ee.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+n+"`: Expected "+o+" "+i+", received "+r+".")}function m(){return new te(ee.APP_DELETED,"The Firebase app was deleted.")}function g(t){return new te(ee.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function y(t,e){return new te(ee.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function R(t){throw new te(ee.INTERNAL_ERROR,"Internal error: "+t)}function E(t){switch(t){case ne.RAW:case ne.BASE64:case ne.BASE64URL:case ne.DATA_URL:return;default:throw"Expected one of the event types: ["+ne.RAW+", "+ne.BASE64+", "+ne.BASE64URL+", "+ne.DATA_URL+"]."}}function w(t,e){switch(t){case ne.RAW:return new re(U(e));case ne.BASE64:case ne.BASE64URL:return new re(A(t,e));case ne.DATA_URL:return new re(N(e),O(e))}throw o()}function U(t){for(var e=[],n=0;n>6,128|63&r);else if(55296==(64512&r)){var o=n>18,128|r>>12&63,128|r>>6&63,128|63&r)}else e.push(239,191,189)}else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function T(t){var e;try{e=decodeURIComponent(t)}catch(t){throw y(ne.DATA_URL,"Malformed data URL.")}return U(e)}function A(t,e){switch(t){case ne.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r){var o=n?"-":"_";throw y(t,"Invalid character '"+o+"' found: is it base64url encoded?")}break;case ne.BASE64URL:var i=-1!==e.indexOf("+"),a=-1!==e.indexOf("/");if(i||a){var o=i?"+":"/";throw y(t,"Invalid character '"+o+"' found: is it base64 encoded?")}e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw y(t,"Invalid character found")}for(var u=new Uint8Array(s.length),c=0;c=e.length)&&t.substring(t.length-e.length)===e}function S(t){switch(t){case ae.RUNNING:case ae.PAUSING:case ae.CANCELING:return se.RUNNING;case ae.PAUSED:return se.PAUSED;case ae.SUCCESS:return se.SUCCESS;case ae.CANCELED:return se.CANCELED;case ae.ERROR:default:return se.ERROR}}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function I(t,e){for(var n in t)k(t,n)&&e(n,t[n])}function L(t){if(null==t)return{};var e={};return I(t,function(t,n){e[t]=n}),e}function P(t){return new Promise(t)}function x(t){return Promise.resolve(t)}function D(t){return Promise.reject(t)}function M(t){return null!=t}function W(t){return void 0!==t}function B(t){return"function"==typeof t}function G(t){return"object"==typeof t}function j(t){return G(t)&&null!==t}function q(t){return G(t)&&!Array.isArray(t)}function F(t){return"string"==typeof t||t instanceof String}function H(t){return"number"==typeof t||t instanceof Number}function z(t){return X()&&t instanceof Blob}function X(){return"undefined"!=typeof Blob}function V(t){var e;try{e=JSON.parse(t)}catch(t){return null}return q(e)?e:null}function K(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}function Z(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}function J(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Q(t){return Vt+Zt+t}function Y(t){return Kt+Zt+t}function $(t){return Vt+Jt+t}function tt(t){var e=encodeURIComponent,n="?";return I(t,function(t,r){var o=e(t)+"="+e(r);n=n+o+"&"}),n=n.slice(0,-1)}function et(t,e){return e}function nt(t){return!F(t)||t.length<2?t:(t=t,J(t))}function rt(){function t(t,e){return nt(e)}function e(t,e){return M(e)?+e:e}function n(t,e){if(!(F(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,o=t.fullPath;return Y("/b/"+n(r)+"/o/"+n(o))+tt({alt:"media",token:e})})}if(pe)return pe;var r=[];r.push(new he("bucket")),r.push(new he("generation")),r.push(new he("metageneration")),r.push(new he("name","fullPath",!0));var o=new he("name");o.xform=t,r.push(o);var i=new he("size");return i.xform=e,r.push(i),r.push(new he("timeCreated")),r.push(new he("updated")),r.push(new he("md5Hash",null,!0)),r.push(new he("cacheControl",null,!0)),r.push(new he("contentDisposition",null,!0)),r.push(new he("contentEncoding",null,!0)),r.push(new he("contentLanguage",null,!0)),r.push(new he("contentType",null,!0)),r.push(new he("metadata","customMetadata",!0)),r.push(new he("downloadTokens","downloadURLs",!1,n)),pe=r}function ot(t,e){function n(){var n=t.bucket,r=t.fullPath,o=new le(n,r);return e.makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function it(t,e,n){var r={};r.type="file";for(var o=n.length,i=0;i=0))throw"Expected a number 0 or greater."}return new fe(t)}function _t(t,e){function n(e){if(!(null===e||M(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)}return new fe(n,e)}function vt(t){function e(t){if(null!==t&&!B(t))throw"Expected a Function."}return new fe(e,t)}function bt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function mt(){for(var t=[],e=0;e0&&(h=Math.min(h,o));var p=c.current,_=p+h,v=h===l?"upload, finalize":"upload",b={"X-Goog-Upload-Command":v,"X-Goog-Upload-Offset":c.current},m=r.slice(p,_);if(null===m)throw f();var g=e.maxUploadRetryTime(),y=new _e(n,"POST",u,g);return y.headers=b,y.body=m.uploadData(),y.progressCallback=s||null,y.errorHandler=Tt(t),y}function Mt(t){return function(){for(var e=[],n=0;n0&&(t.Authorization="Firebase "+e)}function jt(t){var e=void 0!==Xt.default?Xt.default.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}function qt(t,e,n){var r=tt(t.urlParams),o=t.url+r,i=L(t.headers);return Gt(i,e),jt(i),new Ue(o,t.method,i,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}function Ft(t,e,n){return new Ae(t,new ce,n)}function Ht(t){var e={TaskState:se,TaskEvent:ie,StringFormat:ne,Storage:Ae,Reference:ye};t.INTERNAL.registerService(Oe,Ft,e,void 0,!0)}Object.defineProperty(e,"__esModule",{value:!0});var zt,Xt=n(6),Vt="https://firebasestorage.googleapis.com",Kt="https://firebasestorage.googleapis.com",Zt="/v0",Jt="/v0",Qt=12e4,Yt=6e4,$t=-9007199254740991,te=function(){function t(t,e){this.t=r(t),this.e="Firebase Storage: "+e,this.n=null,this.r="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return r(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.n},t.prototype.setServerResponseProp=function(t){this.n=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.r},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.n},enumerable:!0,configurable:!0}),t}(),ee={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"},ne={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},re=function(){function t(t,e){this.data=t,this.contentType=e||null}return t}(),oe=function(){function t(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw y(ne.DATA_URL,"Must be formatted 'data:[][;base64],");var n=e[1]||null;null!=n&&(this.base64=C(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=t.substring(t.indexOf(",")+1)}return t}(),ie={STATE_CHANGED:"state_changed"},ae={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},se={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(zt=zt||(zt={}));var ue=function(){function t(){var t=this;this.o=!1,this.i=new XMLHttpRequest,this.a=zt.NO_ERROR,this.s=P(function(e,n){t.i.addEventListener("abort",function(n){t.a=zt.ABORT,e(t)}),t.i.addEventListener("error",function(n){t.a=zt.NETWORK_ERROR,e(t)}),t.i.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var o=this;if(this.o)throw R("cannot .send() more than once");return this.o=!0,this.i.open(e,t,!0),M(r)&&I(r,function(t,e){o.i.setRequestHeader(t,""+e)}),M(n)?this.i.send(n):this.i.send(),this.s},t.prototype.getErrorCode=function(){if(!this.o)throw R("cannot .getErrorCode() before sending");return this.a},t.prototype.getStatus=function(){if(!this.o)throw R("cannot .getStatus() before sending");try{return this.i.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.o)throw R("cannot .getResponseText() before sending");return this.i.responseText},t.prototype.abort=function(){this.i.abort()},t.prototype.getResponseHeader=function(t){return this.i.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.removeEventListener("progress",t)},t}(),ce=function(){function t(){}return t.prototype.createXhrIo=function(){return new ue},t}(),le=function(){function t(t,e){this.bucket=t,this.u=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.u},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw p(e)},t.makeFromUrl=function(e){function n(t){"/"===t.path.charAt(t.path.length-1)&&(t.u=t.u.slice(0,-1))}function r(t){t.u=decodeURIComponent(t.path)}for(var o=null,i=RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),a={bucket:1,path:3},s=RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),u={bucket:1,path:3},c=[{regex:i,indices:a,postModify:n},{regex:s,indices:u,postModify:r}],l=0;l262144},t.prototype.M=function(){this.k===ae.RUNNING&&null===this.m&&(this.C?null===this.b?this.G():this.f?this.j():this.d?this.q():this.F():this.H())},t.prototype.z=function(t){var e=this;this.U.getAuthToken().then(function(n){switch(e.k){case ae.RUNNING:t(n);break;case ae.CANCELING:e.P(ae.CANCELED);break;case ae.PAUSING:e.P(ae.PAUSED)}})},t.prototype.G=function(){var t=this;this.z(function(e){var n=Pt(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.b=e,t.f=!1,t.L()},t.I)})},t.prototype.j=function(){var t=this,e=this.b;this.z(function(n){var r=xt(t.U,t.T,e,t.A),o=t.U.makeRequest(r,n);t.m=o,o.getPromise().then(function(e){e=e,t.m=null,t.B(e.current),t.f=!1,e.finalized&&(t.d=!0),t.L()},t.I)})},t.prototype.F=function(){var t=this,e=262144*this.g,n=new ve(this.p,this.A.size()),r=this.b;this.z(function(o){var i;try{i=Dt(t.T,t.U,r,t.A,e,t.O,n,t.W())}catch(e){return t.v=e,void t.P(ae.ERROR)}var a=t.U.makeRequest(i,o);t.m=a,a.getPromise().then(function(e){t.X(),t.m=null,t.B(e.current),e.finalized?(t.N=e.metadata,t.P(ae.SUCCESS)):t.L()},t.I)})},t.prototype.X=function(){262144*this.g<33554432&&(this.g*=2)},t.prototype.q=function(){var t=this;this.z(function(e){var n=Nt(t.U,t.T,t.O),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.P(ae.SUCCESS)},t.x)})},t.prototype.H=function(){var t=this;this.z(function(e){var n=It(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.B(t.A.size()),t.P(ae.SUCCESS)},t.I)})},t.prototype.B=function(t){var e=this.p;this.p=t,this.p!==e&&this.V()},t.prototype.P=function(t){if(this.k!==t)switch(t){case ae.CANCELING:case ae.PAUSING:this.k=t,null!==this.m&&this.m.cancel();break;case ae.RUNNING:var e=this.k===ae.PAUSED;this.k=t,e&&(this.V(),this.M());break;case ae.PAUSED:this.k=t,this.V();break;case ae.CANCELED:this.v=l(),this.k=t,this.V();break;case ae.ERROR:case ae.SUCCESS:this.k=t,this.V()}},t.prototype.L=function(){switch(this.k){case ae.PAUSING:this.P(ae.PAUSED);break;case ae.CANCELING:this.P(ae.CANCELED);break;case ae.RUNNING:this.M()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=S(this.k);return new me(this.p,this.A.size(),t,this.N,this,this.w)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(e){if(t!==ie.STATE_CHANGED)throw"Expected one of the event types: ["+ie.STATE_CHANGED+"]."}function i(t){try{return void c(t)}catch(t){}try{if(l(t),!(W(t.next)||W(t.error)||W(t.complete)))throw"";return}catch(t){throw u}}function a(t){function e(e,n,o){null!==t&&ct("on",t,arguments);var i=new be(e,n,r);return h.K(i),function(){h.Z(i)}}return e}function s(t){if(null===t)throw u;i(t)}void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var u="Expected a function or an Object with one of `next`, `error`, `complete` properties.",c=vt(!0).validator,l=_t(null,!0).validator;ct("on",[ht(o),_t(i,!0),vt(!0),vt(!0)],arguments);var h=this,p=[_t(s),vt(!0),vt(!0)];return W(e)||W(n)||W(r)?a(null)(e,n,r):a(p)},t.prototype.then=function(t,e){return this.D.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.K=function(t){this._.push(t),this.J(t)},t.prototype.Z=function(t){Et(this._,t)},t.prototype.V=function(){var t=this;this.Q(),Rt(this._).forEach(function(e){t.J(e)})},t.prototype.Q=function(){if(null!==this.y){var t=!0;switch(S(this.k)){case se.SUCCESS:Mt(this.y.bind(null,this.snapshot))();break;case se.CANCELED:case se.ERROR:Mt(this.R.bind(null,this.v))();break;default:t=!1}t&&(this.y=null,this.R=null)}},t.prototype.J=function(t){switch(S(this.k)){case se.RUNNING:case se.PAUSED:null!==t.next&&Mt(t.next.bind(t,this.snapshot))();break;case se.SUCCESS:null!==t.complete&&Mt(t.complete.bind(t))();break;case se.CANCELED:case se.ERROR:null!==t.error&&Mt(t.error.bind(t,this.v))();break;default:null!==t.error&&Mt(t.error.bind(t,this.v))()}},t.prototype.resume=function(){ct("resume",[],arguments);var t=this.k===ae.PAUSED||this.k===ae.PAUSING;return t&&this.P(ae.RUNNING),t},t.prototype.pause=function(){ct("pause",[],arguments);var t=this.k===ae.RUNNING;return t&&this.P(ae.PAUSING),t},t.prototype.cancel=function(){ct("cancel",[],arguments);var t=this.k===ae.RUNNING||this.k===ae.PAUSING;return t&&this.P(ae.CANCELING),t},t}(),ye=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof le?e:le.makeFromUrl(e)}return t.prototype.toString=function(){return ct("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return rt()},t.prototype.child=function(t){ct("child",[ht()],arguments);var e=Z(this.location.path,t),n=new le(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=K(this.location.path);if(null===t)return null;var e=new le(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new le(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return J(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),ct("put",[pt(),ft(!0)],arguments),this.Y("put"),new ge(this,this.authWrapper,this.location,this.mappings(),new de(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=ne.RAW),ct("putString",[ht(),ht(E,!0),ft(!0)],arguments),this.Y("putString");var r=w(e,t),o=L(n);return!M(o.contentType)&&M(r.contentType)&&(o.contentType=r.contentType),new ge(this,this.authWrapper,this.location,this.mappings(),new de(r.data,!0),o)},t.prototype.delete=function(){ct("delete",[],arguments),this.Y("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Ct(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){ct("getMetadata",[],arguments),this.Y("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Nt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){ct("updateMetadata",[ft()],arguments),this.Y("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=Ot(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return ct("getDownloadURL",[],arguments),this.Y("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(M(e))return e;throw _()})},t.prototype.Y=function(t){if(""===this.location.path)throw g(t)},t}(),Re=function(){function t(t){this.D=D(t)}return t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Ee=function(){function t(){this.$={},this.tt=$t}return t.prototype.addRequest=function(t){function e(){delete r.$[n]}var n=this.tt;this.tt++,this.$[n]=t;var r=this;t.getPromise().then(e,e)},t.prototype.clear=function(){I(this.$,function(t,e){e&&e.cancel(!0)}),this.$={}},t}(),we=function(){function t(e,n,r,o,i){if(this.et=null,this.nt=!1,this.rt=e,null!==this.rt){var a=this.rt.options;M(a)&&(this.et=t.ot(a))}this.it=n,this.at=r,this.st=i,this.ut=o,this.ct=Qt,this.lt=Yt,this.ht=new Ee}return t.ot=function(t){var e=t.storageBucket||null;return null==e?null:le.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.rt&&M(this.rt.INTERNAL)&&M(this.rt.INTERNAL.getToken)?this.rt.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):x(null)},t.prototype.bucket=function(){if(this.nt)throw m();return this.et},t.prototype.service=function(){return this.ut},t.prototype.makeStorageReference=function(t){return this.it(this,t)},t.prototype.makeRequest=function(t,e){if(this.nt)return new Re(m());var n=this.at(t,e,this.st);return this.ht.addRequest(n),n},t.prototype.deleteApp=function(){this.nt=!0,this.rt=null,this.ht.clear()},t.prototype.maxUploadRetryTime=function(){return this.lt},t.prototype.setMaxUploadRetryTime=function(t){this.lt=t},t.prototype.maxOperationRetryTime=function(){return this.ct},t.prototype.setMaxOperationRetryTime=function(t){this.ct=t},t}(),Ue=function(){function t(t,e,n,r,o,i,a,s,u,c,l){this.pt=null,this.ft=null,this.y=null,this.R=null,this.dt=!1,this._t=!1,this.vt=t,this.bt=e,this.mt=n,this.gt=r,this.yt=o.slice(),this.Rt=i.slice(),this.Et=a,this.wt=s,this.Ut=c,this.Tt=u,this.st=l;var h=this;this.D=P(function(t,e){h.y=t,h.R=e,h.M()})}return t.prototype.M=function(){function t(t,e){function r(t){var e=t.loaded,r=t.lengthComputable?t.total:-1;null!==n.Ut&&n.Ut(e,r)}if(e)return void t(!1,new Te(!1,null,!0));var o=n.st.createXhrIo();n.pt=o,null!==n.Ut&&o.addUploadProgressListener(r),o.send(n.vt,n.bt,n.gt,n.mt).then(function(e){null!==n.Ut&&e.removeUploadProgressListener(r),n.pt=null,e=e;var o=e.getErrorCode()===zt.NO_ERROR,i=e.getStatus();if(!o||n.At(i)){var a=e.getErrorCode()===zt.ABORT;return void t(!1,new Te(!1,null,a))}var s=yt(n.yt,i);t(!0,new Te(s,e))})}function e(t,e){var r=n.y,i=n.R,a=e.xhr;if(e.wasSuccessCode)try{var s=n.Et(a,a.getResponseText());W(s)?r(s):r()}catch(t){i(t)}else if(null!==a){var u=o();u.setServerResponseProp(a.getResponseText()),i(n.wt?n.wt(a,u):u)}else if(e.canceled){var u=n._t?m():l();i(u)}else{var u=c();i(u)}}var n=this;this.dt?e(!1,new Te(!1,null,!0)):this.ft=Wt(t,e,this.Tt)},t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){this.dt=!0,this._t=t||!1,null!==this.ft&&Bt(this.ft),null!==this.pt&&this.pt.abort()},t.prototype.At=function(t){var e=t>=500&&t<600,n=[408,429],r=yt(n,t),o=yt(this.Rt,t);return e||r||o},t}(),Te=function(){function t(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}return t}(),Ae=function(){function t(t,e,n){function r(t,e){return new ye(t,e)}if(this.et=null,this.U=new we(t,r,qt,this,e),this.rt=t,null!=n)this.et=le.makeFromBucketSpec(n);else{var o=this.U.bucket();null!=o&&(this.et=new le(o,""))}this.Nt=new Ne(this)}return t.prototype.ref=function(t){function e(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."}if(ct("ref",[ht(e,!0)],arguments),null==this.et)throw Error("No Storage Bucket defined in Firebase Options.");var n=new ye(this.U,this.et);return null!=t?n.child(t):n},t.prototype.refFromURL=function(t){function e(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{le.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}}return ct("refFromURL",[ht(e,!1)],arguments),new ye(this.U,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.U.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){ct("setMaxUploadRetryTime",[dt()],arguments),this.U.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.U.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){ct("setMaxOperationRetryTime",[dt()],arguments),this.U.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.rt},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.Nt},enumerable:!0,configurable:!0}),t}(),Ne=function(){function t(t){this.ut=t}return t.prototype.delete=function(){return this.ut.U.deleteApp(),x(void 0)},t}();e.registerStorage=Ht;var Oe="storage";Ht(Xt.default)}},[118])}catch(t){throw Error("Cannot instantiate firebase-storage.js - be sure to load firebase-app.js first.")} +try{webpackJsonpFirebase([2],{122:function(t,e,n){n(123)},123:function(t,e,n){"use strict";function r(t){return"storage/"+t}function o(){return new te(ee.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function i(t){return new te(ee.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function a(t){return new te(ee.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function s(){return new te(ee.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}function u(t){return new te(ee.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function c(){return new te(ee.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function l(){return new te(ee.CANCELED,"User canceled the upload/download.")}function h(t){return new te(ee.INVALID_URL,"Invalid URL '"+t+"'.")}function p(t){return new te(ee.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function f(){return new te(ee.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function d(){return new te(ee.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function _(){return new te(ee.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function v(t,e,n){return new te(ee.INVALID_ARGUMENT,"Invalid argument in `"+e+"` at index "+t+": "+n)}function b(t,e,n,r){var o,i;return t===e?(o=t,i=1===t?"argument":"arguments"):(o="between "+t+" and "+e,i="arguments"),new te(ee.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+n+"`: Expected "+o+" "+i+", received "+r+".")}function m(){return new te(ee.APP_DELETED,"The Firebase app was deleted.")}function g(t){return new te(ee.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function y(t,e){return new te(ee.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function R(t){throw new te(ee.INTERNAL_ERROR,"Internal error: "+t)}function E(t){switch(t){case ne.RAW:case ne.BASE64:case ne.BASE64URL:case ne.DATA_URL:return;default:throw"Expected one of the event types: ["+ne.RAW+", "+ne.BASE64+", "+ne.BASE64URL+", "+ne.DATA_URL+"]."}}function w(t,e){switch(t){case ne.RAW:return new re(U(e));case ne.BASE64:case ne.BASE64URL:return new re(A(t,e));case ne.DATA_URL:return new re(N(e),O(e))}throw o()}function U(t){for(var e=[],n=0;n>6,128|63&r);else if(55296==(64512&r)){var o=n>18,128|r>>12&63,128|r>>6&63,128|63&r)}else e.push(239,191,189)}else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function T(t){var e;try{e=decodeURIComponent(t)}catch(t){throw y(ne.DATA_URL,"Malformed data URL.")}return U(e)}function A(t,e){switch(t){case ne.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r){var o=n?"-":"_";throw y(t,"Invalid character '"+o+"' found: is it base64url encoded?")}break;case ne.BASE64URL:var i=-1!==e.indexOf("+"),a=-1!==e.indexOf("/");if(i||a){var o=i?"+":"/";throw y(t,"Invalid character '"+o+"' found: is it base64 encoded?")}e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw y(t,"Invalid character found")}for(var u=new Uint8Array(s.length),c=0;c=e.length)&&t.substring(t.length-e.length)===e}function S(t){switch(t){case ae.RUNNING:case ae.PAUSING:case ae.CANCELING:return se.RUNNING;case ae.PAUSED:return se.PAUSED;case ae.SUCCESS:return se.SUCCESS;case ae.CANCELED:return se.CANCELED;case ae.ERROR:default:return se.ERROR}}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function I(t,e){for(var n in t)k(t,n)&&e(n,t[n])}function L(t){if(null==t)return{};var e={};return I(t,function(t,n){e[t]=n}),e}function P(t){return new Promise(t)}function x(t){return Promise.resolve(t)}function D(t){return Promise.reject(t)}function M(t){return null!=t}function W(t){return void 0!==t}function B(t){return"function"==typeof t}function G(t){return"object"==typeof t}function j(t){return G(t)&&null!==t}function q(t){return G(t)&&!Array.isArray(t)}function F(t){return"string"==typeof t||t instanceof String}function H(t){return"number"==typeof t||t instanceof Number}function z(t){return X()&&t instanceof Blob}function X(){return"undefined"!=typeof Blob}function V(t){var e;try{e=JSON.parse(t)}catch(t){return null}return q(e)?e:null}function K(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}function Z(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}function J(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Q(t){return Vt+Zt+t}function Y(t){return Kt+Zt+t}function $(t){return Vt+Jt+t}function tt(t){var e=encodeURIComponent,n="?";return I(t,function(t,r){var o=e(t)+"="+e(r);n=n+o+"&"}),n=n.slice(0,-1)}function et(t,e){return e}function nt(t){return!F(t)||t.length<2?t:(t=t,J(t))}function rt(){function t(t,e){return nt(e)}function e(t,e){return M(e)?+e:e}function n(t,e){if(!(F(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,o=t.fullPath;return Y("/b/"+n(r)+"/o/"+n(o))+tt({alt:"media",token:e})})}if(pe)return pe;var r=[];r.push(new he("bucket")),r.push(new he("generation")),r.push(new he("metageneration")),r.push(new he("name","fullPath",!0));var o=new he("name");o.xform=t,r.push(o);var i=new he("size");return i.xform=e,r.push(i),r.push(new he("timeCreated")),r.push(new he("updated")),r.push(new he("md5Hash",null,!0)),r.push(new he("cacheControl",null,!0)),r.push(new he("contentDisposition",null,!0)),r.push(new he("contentEncoding",null,!0)),r.push(new he("contentLanguage",null,!0)),r.push(new he("contentType",null,!0)),r.push(new he("metadata","customMetadata",!0)),r.push(new he("downloadTokens","downloadURLs",!1,n)),pe=r}function ot(t,e){function n(){var n=t.bucket,r=t.fullPath,o=new le(n,r);return e.makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function it(t,e,n){var r={};r.type="file";for(var o=n.length,i=0;i=0))throw"Expected a number 0 or greater."}return new fe(t)}function _t(t,e){function n(e){if(!(null===e||M(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)}return new fe(n,e)}function vt(t){function e(t){if(null!==t&&!B(t))throw"Expected a Function."}return new fe(e,t)}function bt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function mt(){for(var t=[],e=0;e0&&(h=Math.min(h,o));var p=c.current,_=p+h,v=h===l?"upload, finalize":"upload",b={"X-Goog-Upload-Command":v,"X-Goog-Upload-Offset":c.current},m=r.slice(p,_);if(null===m)throw f();var g=e.maxUploadRetryTime(),y=new _e(n,"POST",u,g);return y.headers=b,y.body=m.uploadData(),y.progressCallback=s||null,y.errorHandler=Tt(t),y}function Mt(t){return function(){for(var e=[],n=0;n0&&(t.Authorization="Firebase "+e)}function jt(t){var e=void 0!==Xt.default?Xt.default.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}function qt(t,e,n){var r=tt(t.urlParams),o=t.url+r,i=L(t.headers);return Gt(i,e),jt(i),new Ue(o,t.method,i,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}function Ft(t,e,n){return new Ae(t,new ce,n)}function Ht(t){var e={TaskState:se,TaskEvent:ie,StringFormat:ne,Storage:Ae,Reference:ye};t.INTERNAL.registerService(Oe,Ft,e,void 0,!0)}Object.defineProperty(e,"__esModule",{value:!0});var zt,Xt=n(7),Vt="https://firebasestorage.googleapis.com",Kt="https://firebasestorage.googleapis.com",Zt="/v0",Jt="/v0",Qt=12e4,Yt=6e4,$t=-9007199254740991,te=function(){function t(t,e){this.t=r(t),this.e="Firebase Storage: "+e,this.n=null,this.r="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return r(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.n},t.prototype.setServerResponseProp=function(t){this.n=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.r},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.n},enumerable:!0,configurable:!0}),t}(),ee={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"},ne={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},re=function(){function t(t,e){this.data=t,this.contentType=e||null}return t}(),oe=function(){function t(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw y(ne.DATA_URL,"Must be formatted 'data:[][;base64],");var n=e[1]||null;null!=n&&(this.base64=C(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=t.substring(t.indexOf(",")+1)}return t}(),ie={STATE_CHANGED:"state_changed"},ae={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},se={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(zt||(zt={}));var ue=function(){function t(){var t=this;this.o=!1,this.i=new XMLHttpRequest,this.a=zt.NO_ERROR,this.s=P(function(e,n){t.i.addEventListener("abort",function(n){t.a=zt.ABORT,e(t)}),t.i.addEventListener("error",function(n){t.a=zt.NETWORK_ERROR,e(t)}),t.i.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var o=this;if(this.o)throw R("cannot .send() more than once");return this.o=!0,this.i.open(e,t,!0),M(r)&&I(r,function(t,e){o.i.setRequestHeader(t,""+e)}),M(n)?this.i.send(n):this.i.send(),this.s},t.prototype.getErrorCode=function(){if(!this.o)throw R("cannot .getErrorCode() before sending");return this.a},t.prototype.getStatus=function(){if(!this.o)throw R("cannot .getStatus() before sending");try{return this.i.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.o)throw R("cannot .getResponseText() before sending");return this.i.responseText},t.prototype.abort=function(){this.i.abort()},t.prototype.getResponseHeader=function(t){return this.i.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.removeEventListener("progress",t)},t}(),ce=function(){function t(){}return t.prototype.createXhrIo=function(){return new ue},t}(),le=function(){function t(t,e){this.bucket=t,this.u=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.u},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw p(e)},t.makeFromUrl=function(e){function n(t){"/"===t.path.charAt(t.path.length-1)&&(t.u=t.u.slice(0,-1))}function r(t){t.u=decodeURIComponent(t.path)}for(var o=null,i=RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),a={bucket:1,path:3},s=RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),u={bucket:1,path:3},c=[{regex:i,indices:a,postModify:n},{regex:s,indices:u,postModify:r}],l=0;l262144},t.prototype.M=function(){this.k===ae.RUNNING&&null===this.m&&(this.C?null===this.b?this.G():this.f?this.j():this.d?this.q():this.F():this.H())},t.prototype.z=function(t){var e=this;this.U.getAuthToken().then(function(n){switch(e.k){case ae.RUNNING:t(n);break;case ae.CANCELING:e.P(ae.CANCELED);break;case ae.PAUSING:e.P(ae.PAUSED)}})},t.prototype.G=function(){var t=this;this.z(function(e){var n=Pt(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.b=e,t.f=!1,t.L()},t.I)})},t.prototype.j=function(){var t=this,e=this.b;this.z(function(n){var r=xt(t.U,t.T,e,t.A),o=t.U.makeRequest(r,n);t.m=o,o.getPromise().then(function(e){e=e,t.m=null,t.B(e.current),t.f=!1,e.finalized&&(t.d=!0),t.L()},t.I)})},t.prototype.F=function(){var t=this,e=262144*this.g,n=new ve(this.p,this.A.size()),r=this.b;this.z(function(o){var i;try{i=Dt(t.T,t.U,r,t.A,e,t.O,n,t.W())}catch(e){return t.v=e,void t.P(ae.ERROR)}var a=t.U.makeRequest(i,o);t.m=a,a.getPromise().then(function(e){t.X(),t.m=null,t.B(e.current),e.finalized?(t.N=e.metadata,t.P(ae.SUCCESS)):t.L()},t.I)})},t.prototype.X=function(){262144*this.g<33554432&&(this.g*=2)},t.prototype.q=function(){var t=this;this.z(function(e){var n=Nt(t.U,t.T,t.O),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.P(ae.SUCCESS)},t.x)})},t.prototype.H=function(){var t=this;this.z(function(e){var n=It(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.B(t.A.size()),t.P(ae.SUCCESS)},t.I)})},t.prototype.B=function(t){var e=this.p;this.p=t,this.p!==e&&this.V()},t.prototype.P=function(t){if(this.k!==t)switch(t){case ae.CANCELING:case ae.PAUSING:this.k=t,null!==this.m&&this.m.cancel();break;case ae.RUNNING:var e=this.k===ae.PAUSED;this.k=t,e&&(this.V(),this.M());break;case ae.PAUSED:this.k=t,this.V();break;case ae.CANCELED:this.v=l(),this.k=t,this.V();break;case ae.ERROR:case ae.SUCCESS:this.k=t,this.V()}},t.prototype.L=function(){switch(this.k){case ae.PAUSING:this.P(ae.PAUSED);break;case ae.CANCELING:this.P(ae.CANCELED);break;case ae.RUNNING:this.M()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=S(this.k);return new me(this.p,this.A.size(),t,this.N,this,this.w)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(e){if(t!==ie.STATE_CHANGED)throw"Expected one of the event types: ["+ie.STATE_CHANGED+"]."}function i(t){try{return void c(t)}catch(t){}try{if(l(t),!(W(t.next)||W(t.error)||W(t.complete)))throw"";return}catch(t){throw u}}function a(t){function e(e,n,o){null!==t&&ct("on",t,arguments);var i=new be(e,n,r);return h.K(i),function(){h.Z(i)}}return e}function s(t){if(null===t)throw u;i(t)}void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var u="Expected a function or an Object with one of `next`, `error`, `complete` properties.",c=vt(!0).validator,l=_t(null,!0).validator;ct("on",[ht(o),_t(i,!0),vt(!0),vt(!0)],arguments);var h=this,p=[_t(s),vt(!0),vt(!0)];return W(e)||W(n)||W(r)?a(null)(e,n,r):a(p)},t.prototype.then=function(t,e){return this.D.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.K=function(t){this._.push(t),this.J(t)},t.prototype.Z=function(t){Et(this._,t)},t.prototype.V=function(){var t=this;this.Q(),Rt(this._).forEach(function(e){t.J(e)})},t.prototype.Q=function(){if(null!==this.y){var t=!0;switch(S(this.k)){case se.SUCCESS:Mt(this.y.bind(null,this.snapshot))();break;case se.CANCELED:case se.ERROR:Mt(this.R.bind(null,this.v))();break;default:t=!1}t&&(this.y=null,this.R=null)}},t.prototype.J=function(t){switch(S(this.k)){case se.RUNNING:case se.PAUSED:null!==t.next&&Mt(t.next.bind(t,this.snapshot))();break;case se.SUCCESS:null!==t.complete&&Mt(t.complete.bind(t))();break;case se.CANCELED:case se.ERROR:null!==t.error&&Mt(t.error.bind(t,this.v))();break;default:null!==t.error&&Mt(t.error.bind(t,this.v))()}},t.prototype.resume=function(){ct("resume",[],arguments);var t=this.k===ae.PAUSED||this.k===ae.PAUSING;return t&&this.P(ae.RUNNING),t},t.prototype.pause=function(){ct("pause",[],arguments);var t=this.k===ae.RUNNING;return t&&this.P(ae.PAUSING),t},t.prototype.cancel=function(){ct("cancel",[],arguments);var t=this.k===ae.RUNNING||this.k===ae.PAUSING;return t&&this.P(ae.CANCELING),t},t}(),ye=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof le?e:le.makeFromUrl(e)}return t.prototype.toString=function(){return ct("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return rt()},t.prototype.child=function(t){ct("child",[ht()],arguments);var e=Z(this.location.path,t),n=new le(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=K(this.location.path);if(null===t)return null;var e=new le(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new le(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return J(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),ct("put",[pt(),ft(!0)],arguments),this.Y("put"),new ge(this,this.authWrapper,this.location,this.mappings(),new de(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=ne.RAW),ct("putString",[ht(),ht(E,!0),ft(!0)],arguments),this.Y("putString");var r=w(e,t),o=L(n);return!M(o.contentType)&&M(r.contentType)&&(o.contentType=r.contentType),new ge(this,this.authWrapper,this.location,this.mappings(),new de(r.data,!0),o)},t.prototype.delete=function(){ct("delete",[],arguments),this.Y("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Ct(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){ct("getMetadata",[],arguments),this.Y("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Nt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){ct("updateMetadata",[ft()],arguments),this.Y("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=Ot(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return ct("getDownloadURL",[],arguments),this.Y("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(M(e))return e;throw _()})},t.prototype.Y=function(t){if(""===this.location.path)throw g(t)},t}(),Re=function(){function t(t){this.D=D(t)}return t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Ee=function(){function t(){this.$={},this.tt=$t}return t.prototype.addRequest=function(t){function e(){delete r.$[n]}var n=this.tt;this.tt++,this.$[n]=t;var r=this;t.getPromise().then(e,e)},t.prototype.clear=function(){I(this.$,function(t,e){e&&e.cancel(!0)}),this.$={}},t}(),we=function(){function t(e,n,r,o,i){if(this.et=null,this.nt=!1,this.rt=e,null!==this.rt){var a=this.rt.options;M(a)&&(this.et=t.ot(a))}this.it=n,this.at=r,this.st=i,this.ut=o,this.ct=Qt,this.lt=Yt,this.ht=new Ee}return t.ot=function(t){var e=t.storageBucket||null;return null==e?null:le.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.rt&&M(this.rt.INTERNAL)&&M(this.rt.INTERNAL.getToken)?this.rt.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):x(null)},t.prototype.bucket=function(){if(this.nt)throw m();return this.et},t.prototype.service=function(){return this.ut},t.prototype.makeStorageReference=function(t){return this.it(this,t)},t.prototype.makeRequest=function(t,e){if(this.nt)return new Re(m());var n=this.at(t,e,this.st);return this.ht.addRequest(n),n},t.prototype.deleteApp=function(){this.nt=!0,this.rt=null,this.ht.clear()},t.prototype.maxUploadRetryTime=function(){return this.lt},t.prototype.setMaxUploadRetryTime=function(t){this.lt=t},t.prototype.maxOperationRetryTime=function(){return this.ct},t.prototype.setMaxOperationRetryTime=function(t){this.ct=t},t}(),Ue=function(){function t(t,e,n,r,o,i,a,s,u,c,l){this.pt=null,this.ft=null,this.y=null,this.R=null,this.dt=!1,this._t=!1,this.vt=t,this.bt=e,this.mt=n,this.gt=r,this.yt=o.slice(),this.Rt=i.slice(),this.Et=a,this.wt=s,this.Ut=c,this.Tt=u,this.st=l;var h=this;this.D=P(function(t,e){h.y=t,h.R=e,h.M()})}return t.prototype.M=function(){function t(t,e){function r(t){var e=t.loaded,r=t.lengthComputable?t.total:-1;null!==n.Ut&&n.Ut(e,r)}if(e)return void t(!1,new Te(!1,null,!0));var o=n.st.createXhrIo();n.pt=o,null!==n.Ut&&o.addUploadProgressListener(r),o.send(n.vt,n.bt,n.gt,n.mt).then(function(e){null!==n.Ut&&e.removeUploadProgressListener(r),n.pt=null,e=e;var o=e.getErrorCode()===zt.NO_ERROR,i=e.getStatus();if(!o||n.At(i)){var a=e.getErrorCode()===zt.ABORT;return void t(!1,new Te(!1,null,a))}var s=yt(n.yt,i);t(!0,new Te(s,e))})}function e(t,e){var r=n.y,i=n.R,a=e.xhr;if(e.wasSuccessCode)try{var s=n.Et(a,a.getResponseText());W(s)?r(s):r()}catch(t){i(t)}else if(null!==a){var u=o();u.setServerResponseProp(a.getResponseText()),i(n.wt?n.wt(a,u):u)}else if(e.canceled){var u=n._t?m():l();i(u)}else{var u=c();i(u)}}var n=this;this.dt?e(!1,new Te(!1,null,!0)):this.ft=Wt(t,e,this.Tt)},t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){this.dt=!0,this._t=t||!1,null!==this.ft&&Bt(this.ft),null!==this.pt&&this.pt.abort()},t.prototype.At=function(t){var e=t>=500&&t<600,n=[408,429],r=yt(n,t),o=yt(this.Rt,t);return e||r||o},t}(),Te=function(){function t(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}return t}(),Ae=function(){function t(t,e,n){function r(t,e){return new ye(t,e)}if(this.et=null,this.U=new we(t,r,qt,this,e),this.rt=t,null!=n)this.et=le.makeFromBucketSpec(n);else{var o=this.U.bucket();null!=o&&(this.et=new le(o,""))}this.Nt=new Ne(this)}return t.prototype.ref=function(t){function e(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."}if(ct("ref",[ht(e,!0)],arguments),null==this.et)throw Error("No Storage Bucket defined in Firebase Options.");var n=new ye(this.U,this.et);return null!=t?n.child(t):n},t.prototype.refFromURL=function(t){function e(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{le.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}}return ct("refFromURL",[ht(e,!1)],arguments),new ye(this.U,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.U.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){ct("setMaxUploadRetryTime",[dt()],arguments),this.U.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.U.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){ct("setMaxOperationRetryTime",[dt()],arguments),this.U.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.rt},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.Nt},enumerable:!0,configurable:!0}),t}(),Ne=function(){function t(t){this.ut=t}return t.prototype.delete=function(){return this.ut.U.deleteApp(),x(void 0)},t}();e.registerStorage=Ht;var Oe="storage";Ht(Xt.default)}},[122])}catch(t){throw Error("Cannot instantiate firebase-storage.js - be sure to load firebase-app.js first.")} //# sourceMappingURL=firebase-storage.js.map \ No newline at end of file diff --git a/lib/firebase/firebase-storage.js.map b/lib/firebase/firebase-storage.js.map index 56dd6285..18deffe1 100644 --- a/lib/firebase/firebase-storage.js.map +++ b/lib/firebase/firebase-storage.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///firebase-storage.js","webpack:///./storage/index.js","webpack:///../storage/dist/esm/src/implementation/error.js","webpack:///../storage/dist/esm/src/implementation/string.js","webpack:///../storage/dist/esm/src/implementation/taskenums.js","webpack:///../storage/dist/esm/src/implementation/object.js","webpack:///../storage/dist/esm/src/implementation/promise_external.js","webpack:///../storage/dist/esm/src/implementation/type.js","webpack:///../storage/dist/esm/src/implementation/json.js","webpack:///../storage/dist/esm/src/implementation/path.js","webpack:///../storage/dist/esm/src/implementation/url.js","webpack:///../storage/dist/esm/src/implementation/metadata.js","webpack:///../storage/dist/esm/src/implementation/args.js","webpack:///../storage/dist/esm/src/implementation/fs.js","webpack:///../storage/dist/esm/src/implementation/array.js","webpack:///../storage/dist/esm/src/implementation/requests.js","webpack:///../storage/dist/esm/src/implementation/async.js","webpack:///../storage/dist/esm/src/implementation/backoff.js","webpack:///../storage/dist/esm/src/implementation/request.js","webpack:///../storage/dist/esm/index.js","webpack:///../storage/dist/esm/src/implementation/xhrio.js","webpack:///../storage/dist/esm/src/implementation/constants.js","webpack:///../storage/dist/esm/src/implementation/xhrio_network.js","webpack:///../storage/dist/esm/src/implementation/xhriopool.js","webpack:///../storage/dist/esm/src/implementation/location.js","webpack:///../storage/dist/esm/src/implementation/blob.js","webpack:///../storage/dist/esm/src/implementation/requestinfo.js","webpack:///../storage/dist/esm/src/implementation/observer.js","webpack:///../storage/dist/esm/src/tasksnapshot.js","webpack:///../storage/dist/esm/src/task.js","webpack:///../storage/dist/esm/src/reference.js","webpack:///../storage/dist/esm/src/implementation/failrequest.js","webpack:///../storage/dist/esm/src/implementation/requestmap.js","webpack:///../storage/dist/esm/src/implementation/authwrapper.js","webpack:///../storage/dist/esm/src/service.js"],"names":["webpackJsonpFirebase","118","module","exports","__webpack_require__","119","__webpack_exports__","prependCode","code","unknown","FirebaseStorageError","Code","UNKNOWN","objectNotFound","path","OBJECT_NOT_FOUND","quotaExceeded","bucket","QUOTA_EXCEEDED","unauthenticated","UNAUTHENTICATED","unauthorized","UNAUTHORIZED","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","error_canceled","CANCELED","invalidUrl","url","INVALID_URL","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","cannotSliceBlob","CANNOT_SLICE_BLOB","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","noDownloadURL","NO_DOWNLOAD_URL","invalidArgument","index","fnName","message","INVALID_ARGUMENT","invalidArgumentCount","argMin","argMax","real","countPart","plural","INVALID_ARGUMENT_COUNT","appDeleted","APP_DELETED","invalidRootOperation","name","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","formatValidator","stringFormat","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","dataFromString","string","StringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","b","i","length","c","charCodeAt","push","valid","hi","lo","Uint8Array","percentEncodedBytes_","decoded","decodeURIComponent","e","hasMinus","indexOf","hasUnder","invalidChar","hasPlus","hasSlash","replace","bytes","atob","array","parts","string_DataURLParts","base64","rest","contentType","endsWith","s","end","substring","taskStateFromInternalTaskState","state","InternalTaskState","RUNNING","PAUSING","CANCELING","TaskState","PAUSED","SUCCESS","ERROR","contains","obj","prop","Object","prototype","hasOwnProperty","call","forEach","f","key","clone","val","make","resolver","Promise","promise_external_resolve","value","resolve","promise_external_reject","error","reject","isDef","p","isJustDef","isFunction","isObject","isNonNullObject","isNonArrayObject","Array","isArray","isString","String","isNumber","Number","isNativeBlob","isNativeBlobDefined","Blob","jsonObjectOrNull","JSON","parse","path_parent","lastIndexOf","slice","child","childPath","canonicalChildPath","split","filter","component","join","lastComponent","makeNormalUrl","urlPart","domainBase","apiBaseUrl","makeDownloadUrl","downloadBase","makeUploadUrl","apiUploadBaseUrl","makeQueryString","params","encode","encodeURIComponent","queryPart","nextPart","noXform_","metadata","xformPath","fullPath","getMappings","mappingsXformPath","xformSize","size","xformTokens","tokens","map","token","alt","mappings_","mappings","Mapping","nameMapping","xform","sizeMapping","addRef","authWrapper","generateRef","loc","location_Location","makeStorageReference","defineProperty","get","fromResource","resource","len","mapping","local","server","fromResourceString","resourceString","toResourceString","writable","stringify","metadataValidator","validate","specs","passed","minArgs","maxArgs","optional","validator","Error","and_","v1","v2","stringSpec","opt_validator","opt_optional","stringValidator","args_ArgSpec","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","undefined","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","var_args","_i","arguments","bb","append","sliceBlob","blob","start","webkitSlice","mozSlice","array_contains","elem","array_clone","arraylike","remove","splice","handlerCheck","cndn","metadataHandler","handler","xhr","text","sharedErrorHandler","location","errorHandler","err","newErr","getStatus","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","getMetadata","fullServerUrl","timeout","maxOperationRetryTime","requestInfo","RequestInfo","updateMetadata","body","headers","Content-Type","deleteObject","successCodes","determineContentType_","type","metadataForUpload_","opt_metadata","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","str","Math","random","metadataString","preBlobPart","postBlobPart","blob_FbsBlob","urlParams","maxUploadRetryTime","uploadData","checkResumeHeader_","opt_allowed","status","getResponseHeader","createResumableUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","parseInt","isNaN","ResumableUploadStatus","continueResumableUpload","chunkSize","opt_status","opt_progressCallback","uploadStatus","newCurrent","current","bytesToUpload","total","bytesLeft","min","startByte","endByte","uploadCommand","X-Goog-Upload-Offset","progressCallback","async_async","argsToForward","then","apply","callback","canceled","cancelState","triggerCallback","triggeredCallback","callWithDelay","millis","timeoutId","setTimeout","success","hitTimeout","waitSeconds","waitMillis","stop","wasTimeout","stopped","clearTimeout","id","addAuthHeader_","authToken","addVersionHeader_","number","esm","SDK_VERSION","makeRequest","pool","request_NetworkRequest","method","additionalRetryCodes","factory","app","unused","opt_url","service_Service","xhriopool_XhrIoPool","registerStorage","instance","namespaceExports","TaskEvent","Storage","Reference","reference_Reference","INTERNAL","registerService","STORAGE_TYPE","ErrorCode","defaultMaxOperationRetryTime","defaultMaxUploadRetryTime","minSafeInteger","this","code_","message_","serverResponse_","name_","codeProp","codeEquals","serverResponse","enumerable","configurable","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","INVALID_CHECKSUM","INVALID_EVENT_NAME","NO_DEFAULT_BUCKET","data","opt_contentType","DataURLParts","dataURL","matches","match","middle","STATE_CHANGED","xhrio_network_NetworkXhrIo","NetworkXhrIo","_this","sent_","xhr_","XMLHttpRequest","errorCode_","NO_ERROR","sendPromise_","addEventListener","event","ABORT","NETWORK_ERROR","send","opt_body","opt_headers","open","setRequestHeader","getErrorCode","getResponseText","responseText","abort","header","addUploadProgressListener","listener","upload","removeUploadProgressListener","removeEventListener","XhrIoPool","createXhrIo","Location","path_","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","gsModify","charAt","httpModify","gsRegex","RegExp","gsIndices","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","exec","bucketValue","pathValue","opt_local","opt_writable","opt_xform","ArgSpec","self","FbsBlob","opt_elideCopy","blobType","data_","byteLength","set","size_","type_","realBlob","sliced","buffer","blobby","uint8Arrays","finalLength_1","merged_1","index_1","finalized","observer_Observer","Observer","nextOrObserver","opt_error","opt_complete","next","complete","observer","UploadTaskSnapshot","bytesTransferred","totalBytes","task","ref","urls","task_UploadTask","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","ref_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","state_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","start_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","getAuthToken","createRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","metadataRequest","multipartRequest","transferred","old","notifyObservers_","cancel","wasPaused","externalState","on","completed","typeValidator","_p","nextOrObserverValidator","nextValidator","observerValidator","nextOrObserverMessage","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","onFulfilled","onRejected","catch","notifyObserver_","finishPromise_","triggered","bind","snapshot","resume","pause","toString","newRef","newPath","service","put","throwIfRoot_","putString","delete","getDownloadURL","failrequest_FailRequest","FailRequest","appDelete","requestmap_RequestMap","RequestMap","map_","id_","addRequest","r","unmap","clear","authwrapper_AuthWrapper","AuthWrapper","maker","requestMaker","bucket_","deleted_","app_","options","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","getToken","response","accessToken","_error","request","deleteApp","setMaxUploadRetryTime","time","setMaxOperationRetryTime","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","progressListener","progressEvent","lengthComputable","RequestEndStatus","hitServer","isRetryStatusCode_","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","result","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","Service","authWrapperBucket","internals_","service_ServiceInternals","test","refFromURL","ServiceInternals"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IAExBC,IACA,SAAUC,EAAQC,EAASC,GCOjCA,EAAA,MDgBMC,IACA,SAAUH,EAAQI,EAAqBF,GAE7C,YE2DA,SAAAG,GAAAC,GACA,iBAAAA,EAEA,QAAAC,KAGA,UAAAC,IAAAC,GAAAC,QAFA,kFAIA,QAAAC,GAAAC,GACA,UAAAJ,IAAAC,GAAAI,iBAAA,WAAAD,EAAA,qBAQA,QAAAE,GAAAC,GACA,UAAAP,IAAAC,GAAAO,eAAA,qBACAD,EACA,0EAGA,QAAAE,KAGA,UAAAT,IAAAC,GAAAS,gBAFA,+F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4F,OAAAuF,eAAAqc,EAAA3hB,UAAA,sBACAuF,IAAA,WACA,MAAAwL,MAAA6H,EAAAjN,sBAEA4F,YAAA,EACAC,cAAA,IAEAmQ,EAAA3hB,UAAAqf,sBAAA,SAAAC,GACAlZ,GAAA,yBAAAmB,MAAAU,WACA8I,KAAA6H,EAAAyG,sBAAAC,IAEAvf,OAAAuF,eAAAqc,EAAA3hB,UAAA,yBACAuF,IAAA,WACA,MAAAwL,MAAA6H,EAAA1O,yBAEAqH,YAAA,EACAC,cAAA,IAEAmQ,EAAA3hB,UAAAuf,yBAAA,SAAAD,GACAlZ,GAAA,4BAAAmB,MAAAU,WACA8I,KAAA6H,EAAA2G,yBAAAD,IAEAvf,OAAAuF,eAAAqc,EAAA3hB,UAAA,OACAuF,IAAA,WACA,MAAAwL,MAAAqN,IAEA7M,YAAA,EACAC,cAAA,IAEAzR,OAAAuF,eAAAqc,EAAA3hB,UAAA,YACAuF,IAAA,WACA,MAAAwL,MAAA8Q,IAEAtQ,YAAA,EACAC,cAAA,IAEAmQ,KAMAG,GAAA,WACA,QAAAG,GAAApF,GACA9L,KAAA2N,GAAA7B,EAUA,MAJAoF,GAAAjiB,UAAAid,OAAA,WAEA,MADAlM,MAAA2N,GAAA9F,EAAAwG,YACAze,MAAA8G,KAEAwa,If7IAppB,GAAA,gBAAAoX,EAyBA,IAAAS,IAAA,SAiBAT,IAAAb,GAAA,YnBmoHG,MACO,MAAMrO,GACN,KAAU4F,OACR","file":"firebase-storage.js","sourcesContent":["/*!\n * @license Firebase v4.6.1\n * Build: rev-0ea11f2\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([2],{\n\n/***/ 118:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(119);\n\n\n/***/ }),\n\n/***/ 119:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(6);\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/constants.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nvar apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nvar apiUploadBaseUrl = '/v0';\nfunction setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nvar configOption = 'storageBucket';\n/**\n * 1 minute\n */\nvar shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nvar minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/error.js\n/**\n * Copyright 2017 Google Inc.\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\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\n\nvar errors = {};\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nfunction prependCode(code) {\n return 'storage/' + code;\n}\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nfunction bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nfunction projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nfunction invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nfunction error_canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nfunction invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nfunction noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/string.js\n/**\n * Copyright 2017 Google Inc.\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\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw unknown();\n}\nfunction utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nfunction percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar string_DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nfunction dataURLBytes_(string) {\n var parts = new string_DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nfunction dataURLContentType_(string) {\n var parts = new string_DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/taskenums.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/object.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/promise_external.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nfunction make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nfunction promise_external_resolve(value) {\n return Promise.resolve(value);\n}\nfunction promise_external_reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/type.js\n/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nfunction isDef(p) {\n return p != null;\n}\nfunction isJustDef(p) {\n return p !== void 0;\n}\nfunction isFunction(p) {\n return typeof p === 'function';\n}\nfunction isObject(p) {\n return typeof p === 'object';\n}\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio.js\n/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nvar ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode = ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio_network.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar xhrio_network_NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\n\n\n//# sourceMappingURL=xhrio_network.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhriopool.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Factory-like class for creating XhrIo instances.\n */\nvar xhriopool_XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new xhrio_network_NetworkXhrIo();\n };\n return XhrIoPool;\n}());\n\n\n//# sourceMappingURL=xhriopool.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/json.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nfunction jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/location.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\n/**\n * @struct\n */\nvar location_Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\n\n\n//# sourceMappingURL=location.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/path.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nfunction path_parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nfunction child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/url.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/metadata.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\n\nvar mappings_ = null;\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new location_Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/args.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n }\n else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar args_ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction metadataSpec(opt_optional) {\n return new args_ArgSpec(metadataValidator, opt_optional);\n}\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/fs.js\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nfunction getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/blob.js\n/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\n\n\n\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar blob_FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\n\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/array.js\n/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nfunction array_contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nfunction array_clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestinfo.js\nvar RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\n\n\n//# sourceMappingURL=requestinfo.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requests.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = blob_FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array_contains(allowed, status));\n return status;\n}\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nvar resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/observer.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * @struct\n */\nvar observer_Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) ||\n isDef(opt_error) ||\n isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\n\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/tasksnapshot.js\nvar UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\n\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/async.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nfunction async_async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promise_external_resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/task.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar task_UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = error_canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) ||\n isJustDef(p['error']) ||\n isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n var observer = new observer_Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n var typeOnly = !(isJustDef(nextOrObserver) ||\n isJustDef(error) ||\n isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = array_clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async_async(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async_async(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async_async(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async_async(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\n\n\n//# sourceMappingURL=task.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/reference.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar reference_Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof location_Location) {\n this.location = location;\n }\n else {\n this.location = location_Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path_parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new location_Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n validate('putString', [\n stringSpec(),\n stringSpec(formatValidator, true),\n metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (isDef(url)) {\n return url;\n }\n else {\n throw noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n return Reference;\n}());\n\n\n//# sourceMappingURL=reference.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/failrequest.js\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar failrequest_FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promise_external_reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\n\n\n//# sourceMappingURL=failrequest.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestmap.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * @struct\n */\nvar requestmap_RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\n\n\n//# sourceMappingURL=requestmap.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/authwrapper.js\n\n\n\n\n\n\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar authwrapper_AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new requestmap_RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = location_Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n isDef(this.app_.INTERNAL) &&\n isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promise_external_resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new failrequest_FailRequest(appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\n\n\n//# sourceMappingURL=authwrapper.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/backoff.js\n/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nfunction stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/request.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\n\n\n\n\n\n\n\n\n/**\n * @struct\n * @template T\n */\nvar request_NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array_contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? appDeleted()\n : error_canceled();\n reject(err);\n }\n else {\n var err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array_contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array_contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nfunction addVersionHeader_(headers) {\n var number = typeof esm[\"default\"] !== 'undefined' ? esm[\"default\"].SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new request_NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/service.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar service_Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new reference_Reference(authWrapper, loc);\n }\n this.authWrapper_ = new authwrapper_AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = location_Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new location_Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new service_ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n validate('ref', [stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new reference_Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n location_Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new reference_Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\n\n/**\n * @struct\n */\nvar service_ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return promise_external_resolve(undefined);\n };\n return ServiceInternals;\n}());\n\n\n//# sourceMappingURL=service.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerStorage\"] = registerStorage;\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new service_Service(app, new xhriopool_XhrIoPool(), opt_url);\n}\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: service_Service,\n Reference: reference_Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[118]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-storage.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-storage.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/storage');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./storage/index.js\n// module id = 118\n// module chunks = 2","/**\n * Copyright 2017 Google Inc.\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 */\nimport { configOption } from './constants';\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\nexport { FirebaseStorageError };\nexport var errors = {};\nexport var Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nexport function prependCode(code) {\n return 'storage/' + code;\n}\nexport function unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nexport function objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nexport function bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nexport function projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nexport function quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nexport function unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nexport function unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nexport function retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nexport function invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nexport function canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nexport function invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nexport function invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nexport function invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nexport function noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nexport function cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nexport function serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nexport function noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nexport function invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nexport function invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nexport function appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nexport var StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nexport function formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\nexport { StringData };\nexport function dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw errorsExports.unknown();\n}\nexport function utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nexport function percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nexport function base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nexport function dataURLBytes_(string) {\n var parts = new DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nexport function dataURLContentType_(string) {\n var parts = new DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/string.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport var TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nexport var InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nexport var TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nexport function taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/taskenums.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nexport function contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nexport function forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nexport function clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/object.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nexport function make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nexport function resolve(value) {\n return Promise.resolve(value);\n}\nexport function reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/promise_external.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef(p) {\n return p != null;\n}\nexport function isJustDef(p) {\n return p !== void 0;\n}\nexport function isFunction(p) {\n return typeof p === 'function';\n}\nexport function isObject(p) {\n return typeof p === 'object';\n}\nexport function isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nexport function isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nexport function isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nexport function isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nexport function isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nexport function isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/type.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/json.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nexport function child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport * as constants from './constants';\nimport * as object from './object';\nexport function makeNormalUrl(urlPart) {\n return constants.domainBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeDownloadUrl(urlPart) {\n return constants.downloadBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeUploadUrl(urlPart) {\n return constants.domainBase + constants.apiUploadBaseUrl + urlPart;\n}\nexport function makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n object.forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/url.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nexport function noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\nexport { Mapping };\nvar mappings_ = null;\nexport function xformPath(fullPath) {\n var valid = type.isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return path.lastComponent(fullPath);\n }\n}\nexport function getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (type.isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = type.isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = UrlUtils.makeDownloadUrl(urlPart);\n var queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nexport function addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nexport function fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nexport function fromResourceString(authWrapper, resourceString, mappings) {\n var obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nexport function toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nexport function metadataValidator(p) {\n var validType = p && type.isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/metadata.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as type from './type';\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n }\n else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\nexport { ArgSpec };\nexport function and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nexport function stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function metadataSpec(opt_optional) {\n return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);\n}\nexport function nonNegativeNumberSpec() {\n function validator(p) {\n var valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/args.js\n// module id = null\n// module chunks = ","import * as type from './type';\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (type.isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/fs.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nexport function contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nexport function clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nexport function remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/array.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as array from './array';\nimport { FbsBlob } from './blob';\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as object from './object';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn) {\n if (!cndn) {\n throw errorsExports.unknown();\n }\n}\nexport function metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = MetadataUtils.fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nexport function sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = errorsExports.unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = errorsExports.quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = errorsExports.unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = errorsExports.objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nexport function metadataForUpload_(location, blob, opt_metadata) {\n var metadata = object.clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nexport function multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = MetadataUtils.toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\nexport { ResumableUploadStatus };\nexport function checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array.contains(allowed, status));\n return status;\n}\nexport function createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport var resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw errorsExports.serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requests.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\nimport * as promiseimpl from './promise_external';\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promiseimpl.resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/async.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\nimport firebase from '@firebase/app';\nimport * as array from './array';\nimport * as backoff from './backoff';\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport * as XhrIoExports from './xhrio';\n/**\n * @struct\n * @template T\n */\nvar NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = promiseimpl.make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array.contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = errorsExports.unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? errorsExports.appDeleted()\n : errorsExports.canceled();\n reject(err);\n }\n else {\n var err = errorsExports.retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array.contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array.contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\nexport { RequestEndStatus };\nexport function addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nexport function addVersionHeader_(headers) {\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nexport function makeRequest(requestInfo, authToken, pool) {\n var queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = object.clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/request.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent } from './src/implementation/taskenums';\nimport { TaskState } from './src/implementation/taskenums';\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new Service(app, new XhrIoPool(), opt_url);\n}\nexport function registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode = ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nexport var domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nexport var downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nexport var apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nexport var apiUploadBaseUrl = '/v0';\nexport function setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nexport var configOption = 'storageBucket';\n/**\n * 1 minute\n */\nexport var shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nexport var defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nexport var defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport var minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/constants.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as XhrIoExports from './xhrio';\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = XhrIoExports.ErrorCode.NO_ERROR;\n this.sendPromise_ = promiseimpl.make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(opt_headers)) {\n var headers = opt_headers;\n object.forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (type.isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\nexport { NetworkXhrIo };\n\n//# sourceMappingURL=xhrio_network.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio_network.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { NetworkXhrIo } from './xhrio_network';\n/**\n * Factory-like class for creating XhrIo instances.\n */\nvar XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new NetworkXhrIo();\n };\n return XhrIoPool;\n}());\nexport { XhrIoPool };\n\n//# sourceMappingURL=xhriopool.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhriopool.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\n/**\n * @struct\n */\nvar Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\nexport { Location };\n\n//# sourceMappingURL=location.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/location.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport * as string from './string';\nimport { StringFormat } from './string';\nimport * as type from './type';\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (type.isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (type.isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (type.isString(val)) {\n return string.dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\nexport { FbsBlob };\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/blob.js\n// module id = null\n// module chunks = ","var RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\nexport { RequestInfo };\n\n//# sourceMappingURL=requestinfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestinfo.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * @struct\n */\nvar Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = type.isFunction(nextOrObserver) ||\n type.isDef(opt_error) ||\n type.isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\nexport { Observer };\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/observer.js\n// module id = null\n// module chunks = ","var UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\nexport { UploadTaskSnapshot };\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/tasksnapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\nimport { InternalTaskState } from './implementation/taskenums';\nimport { Observer } from './implementation/observer';\nimport { TaskEvent, TaskState } from './implementation/taskenums';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport * as fbsArgs from './implementation/args';\nimport * as fbsArray from './implementation/array';\nimport { async as fbsAsync } from './implementation/async';\nimport * as errors from './implementation/error';\nimport * as fbsPromiseimpl from './implementation/promise_external';\nimport * as fbsRequests from './implementation/requests';\nimport * as fbsTaskEnums from './implementation/taskenums';\nimport * as typeUtils from './implementation/type';\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = fbsPromiseimpl.make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new fbsRequests.ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = errors.canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = fbsArgs.nullFunctionSpec(true).validator;\n var observerValidator = fbsArgs.looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n fbsArgs.stringSpec(typeValidator),\n fbsArgs.looseObjectSpec(nextOrObserverValidator, true),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n fbsArgs.validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n fbsArgs.validate('on', specs, arguments);\n }\n var observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n fbsArgs.looseObjectSpec(binderNextOrObserverValidator),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n var typeOnly = !(typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n fbsArray.remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = fbsArray.clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n fbsAsync(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n fbsArgs.validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n fbsArgs.validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n fbsArgs.validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\nexport { UploadTask };\n\n//# sourceMappingURL=task.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/task.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport * as args from './implementation/args';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as object from './implementation/object';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport * as fbsString from './implementation/string';\nimport { StringFormat } from './implementation/string';\nimport * as type from './implementation/type';\nimport { UploadTask } from './task';\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof Location) {\n this.location = location;\n }\n else {\n this.location = Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n args.validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return metadata.getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n args.validate('child', [args.stringSpec()], arguments);\n var newPath = path.child(this.location.path, childPath);\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return path.lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n args.validate('put', [args.uploadDataSpec(), args.metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n args.validate('putString', [\n args.stringSpec(),\n args.stringSpec(fbsString.formatValidator, true),\n args.metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = fbsString.dataFromString(format, string);\n var metadata = object.clone(opt_metadata);\n if (!type.isDef(metadata['contentType']) && type.isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n args.validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n args.validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n args.validate('updateMetadata', [args.metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n args.validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (type.isDef(url)) {\n return url;\n }\n else {\n throw errorsExports.noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n };\n return Reference;\n}());\nexport { Reference };\n\n//# sourceMappingURL=reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/reference.js\n// module id = null\n// module chunks = ","import * as promiseimpl from './promise_external';\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promiseimpl.reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\nexport { FailRequest };\n\n//# sourceMappingURL=failrequest.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/failrequest.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as object from './object';\nimport * as constants from './constants';\n/**\n * @struct\n */\nvar RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = constants.minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n object.forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\nexport { RequestMap };\n\n//# sourceMappingURL=requestmap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestmap.js\n// module id = null\n// module chunks = ","import * as constants from './constants';\nimport * as errorsExports from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport * as promiseimpl from './promise_external';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = constants.defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[constants.configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n type.isDef(this.app_.INTERNAL) &&\n type.isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promiseimpl.resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new FailRequest(errorsExports.appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\nexport { AuthWrapper };\n\n//# sourceMappingURL=authwrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/authwrapper.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as fbsPromiseImpl from './implementation/promise_external';\nimport * as RequestExports from './implementation/request';\nimport { Reference } from './reference';\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(app, maker, RequestExports.makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n args.validate('setMaxUploadRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n args.validate('setMaxOperationRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\nexport { Service };\n/**\n * @struct\n */\nvar ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return fbsPromiseImpl.resolve(undefined);\n };\n return ServiceInternals;\n}());\nexport { ServiceInternals };\n\n//# sourceMappingURL=service.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/service.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///firebase-storage.js","webpack:///./storage/index.js","webpack:///../storage/dist/esm/src/implementation/error.js","webpack:///../storage/dist/esm/src/implementation/string.js","webpack:///../storage/dist/esm/src/implementation/taskenums.js","webpack:///../storage/dist/esm/src/implementation/object.js","webpack:///../storage/dist/esm/src/implementation/promise_external.js","webpack:///../storage/dist/esm/src/implementation/type.js","webpack:///../storage/dist/esm/src/implementation/json.js","webpack:///../storage/dist/esm/src/implementation/path.js","webpack:///../storage/dist/esm/src/implementation/url.js","webpack:///../storage/dist/esm/src/implementation/metadata.js","webpack:///../storage/dist/esm/src/implementation/args.js","webpack:///../storage/dist/esm/src/implementation/fs.js","webpack:///../storage/dist/esm/src/implementation/array.js","webpack:///../storage/dist/esm/src/implementation/requests.js","webpack:///../storage/dist/esm/src/implementation/async.js","webpack:///../storage/dist/esm/src/implementation/backoff.js","webpack:///../storage/dist/esm/src/implementation/request.js","webpack:///../storage/dist/esm/index.js","webpack:///../storage/dist/esm/src/implementation/xhrio.js","webpack:///../storage/dist/esm/src/implementation/constants.js","webpack:///../storage/dist/esm/src/implementation/xhrio_network.js","webpack:///../storage/dist/esm/src/implementation/xhriopool.js","webpack:///../storage/dist/esm/src/implementation/location.js","webpack:///../storage/dist/esm/src/implementation/blob.js","webpack:///../storage/dist/esm/src/implementation/requestinfo.js","webpack:///../storage/dist/esm/src/implementation/observer.js","webpack:///../storage/dist/esm/src/tasksnapshot.js","webpack:///../storage/dist/esm/src/task.js","webpack:///../storage/dist/esm/src/reference.js","webpack:///../storage/dist/esm/src/implementation/failrequest.js","webpack:///../storage/dist/esm/src/implementation/requestmap.js","webpack:///../storage/dist/esm/src/implementation/authwrapper.js","webpack:///../storage/dist/esm/src/service.js"],"names":["webpackJsonpFirebase","122","module","exports","__webpack_require__","123","__webpack_exports__","prependCode","code","unknown","FirebaseStorageError","Code","UNKNOWN","objectNotFound","path","OBJECT_NOT_FOUND","quotaExceeded","bucket","QUOTA_EXCEEDED","unauthenticated","UNAUTHENTICATED","unauthorized","UNAUTHORIZED","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","error_canceled","CANCELED","invalidUrl","url","INVALID_URL","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","cannotSliceBlob","CANNOT_SLICE_BLOB","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","noDownloadURL","NO_DOWNLOAD_URL","invalidArgument","index","fnName","message","INVALID_ARGUMENT","invalidArgumentCount","argMin","argMax","real","countPart","plural","INVALID_ARGUMENT_COUNT","appDeleted","APP_DELETED","invalidRootOperation","name","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","formatValidator","stringFormat","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","dataFromString","string","StringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","b","i","length","c","charCodeAt","push","valid","hi","lo","Uint8Array","percentEncodedBytes_","decoded","decodeURIComponent","e","hasMinus","indexOf","hasUnder","invalidChar","hasPlus","hasSlash","replace","bytes","atob","array","parts","string_DataURLParts","base64","rest","contentType","endsWith","s","end","substring","taskStateFromInternalTaskState","state","InternalTaskState","RUNNING","PAUSING","CANCELING","TaskState","PAUSED","SUCCESS","ERROR","contains","obj","prop","Object","prototype","hasOwnProperty","call","forEach","f","key","clone","val","make","resolver","Promise","promise_external_resolve","value","resolve","promise_external_reject","error","reject","isDef","p","isJustDef","isFunction","isObject","isNonNullObject","isNonArrayObject","Array","isArray","isString","String","isNumber","Number","isNativeBlob","isNativeBlobDefined","Blob","jsonObjectOrNull","JSON","parse","path_parent","lastIndexOf","slice","child","childPath","canonicalChildPath","split","filter","component","join","lastComponent","makeNormalUrl","urlPart","domainBase","apiBaseUrl","makeDownloadUrl","downloadBase","makeUploadUrl","apiUploadBaseUrl","makeQueryString","params","encode","encodeURIComponent","queryPart","nextPart","noXform_","metadata","xformPath","fullPath","getMappings","mappingsXformPath","xformSize","size","xformTokens","tokens","map","token","alt","mappings_","mappings","Mapping","nameMapping","xform","sizeMapping","addRef","authWrapper","generateRef","loc","location_Location","makeStorageReference","defineProperty","get","fromResource","resource","len","mapping","local","server","fromResourceString","resourceString","toResourceString","writable","stringify","metadataValidator","validate","specs","passed","minArgs","maxArgs","optional","validator","Error","and_","v1","v2","stringSpec","opt_validator","opt_optional","stringValidator","args_ArgSpec","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","undefined","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","var_args","_i","arguments","bb","append","sliceBlob","blob","start","webkitSlice","mozSlice","array_contains","elem","array_clone","arraylike","remove","splice","handlerCheck","cndn","metadataHandler","handler","xhr","text","sharedErrorHandler","location","errorHandler","err","newErr","getStatus","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","getMetadata","fullServerUrl","timeout","maxOperationRetryTime","requestInfo","RequestInfo","updateMetadata","body","headers","Content-Type","deleteObject","successCodes","determineContentType_","type","metadataForUpload_","opt_metadata","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","str","Math","random","metadataString","preBlobPart","postBlobPart","blob_FbsBlob","urlParams","maxUploadRetryTime","uploadData","checkResumeHeader_","opt_allowed","status","getResponseHeader","createResumableUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","parseInt","isNaN","ResumableUploadStatus","continueResumableUpload","chunkSize","opt_status","opt_progressCallback","uploadStatus","newCurrent","current","bytesToUpload","total","bytesLeft","min","startByte","endByte","uploadCommand","X-Goog-Upload-Offset","progressCallback","async_async","argsToForward","then","apply","callback","canceled","cancelState","triggerCallback","triggeredCallback","callWithDelay","millis","timeoutId","setTimeout","success","hitTimeout","waitSeconds","waitMillis","stop","wasTimeout","stopped","clearTimeout","id","addAuthHeader_","authToken","addVersionHeader_","number","esm","SDK_VERSION","makeRequest","pool","request_NetworkRequest","method","additionalRetryCodes","factory","app","unused","opt_url","service_Service","xhriopool_XhrIoPool","registerStorage","instance","namespaceExports","TaskEvent","Storage","Reference","reference_Reference","INTERNAL","registerService","STORAGE_TYPE","ErrorCode","defaultMaxOperationRetryTime","defaultMaxUploadRetryTime","minSafeInteger","this","code_","message_","serverResponse_","name_","codeProp","codeEquals","serverResponse","enumerable","configurable","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","INVALID_CHECKSUM","INVALID_EVENT_NAME","NO_DEFAULT_BUCKET","data","opt_contentType","DataURLParts","dataURL","matches","match","middle","STATE_CHANGED","xhrio_network_NetworkXhrIo","NetworkXhrIo","_this","sent_","xhr_","XMLHttpRequest","errorCode_","NO_ERROR","sendPromise_","addEventListener","event","ABORT","NETWORK_ERROR","send","opt_body","opt_headers","open","setRequestHeader","getErrorCode","getResponseText","responseText","abort","header","addUploadProgressListener","listener","upload","removeUploadProgressListener","removeEventListener","XhrIoPool","createXhrIo","Location","path_","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","gsModify","charAt","httpModify","gsRegex","RegExp","gsIndices","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","exec","bucketValue","pathValue","opt_local","opt_writable","opt_xform","ArgSpec","self","FbsBlob","opt_elideCopy","blobType","data_","byteLength","set","size_","type_","realBlob","sliced","buffer","blobby","uint8Arrays","finalLength_1","merged_1","index_1","finalized","observer_Observer","Observer","nextOrObserver","opt_error","opt_complete","next","complete","observer","UploadTaskSnapshot","bytesTransferred","totalBytes","task","ref","urls","task_UploadTask","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","ref_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","state_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","start_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","getAuthToken","createRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","metadataRequest","multipartRequest","transferred","old","notifyObservers_","cancel","wasPaused","externalState","on","completed","typeValidator","_p","nextOrObserverValidator","nextValidator","observerValidator","nextOrObserverMessage","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","onFulfilled","onRejected","catch","notifyObserver_","finishPromise_","triggered","bind","snapshot","resume","pause","toString","newRef","newPath","service","put","throwIfRoot_","putString","delete","getDownloadURL","failrequest_FailRequest","FailRequest","appDelete","requestmap_RequestMap","RequestMap","map_","id_","addRequest","r","unmap","clear","authwrapper_AuthWrapper","AuthWrapper","maker","requestMaker","bucket_","deleted_","app_","options","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","getToken","response","accessToken","_error","request","deleteApp","setMaxUploadRetryTime","time","setMaxOperationRetryTime","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","progressListener","progressEvent","lengthComputable","RequestEndStatus","hitServer","isRetryStatusCode_","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","result","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","Service","authWrapperBucket","internals_","service_ServiceInternals","test","refFromURL","ServiceInternals"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IAExBC,IACA,SAAUC,EAAQC,EAASC,GCOjCA,EAAA,MDgBMC,IACA,SAAUH,EAAQI,EAAqBF,GAE7C,YE2DA,SAAAG,GAAAC,GACA,iBAAAA,EAEA,QAAAC,KAGA,UAAAC,IAAAC,GAAAC,QAFA,kFAIA,QAAAC,GAAAC,GACA,UAAAJ,IAAAC,GAAAI,iBAAA,WAAAD,EAAA,qBAQA,QAAAE,GAAAC,GACA,UAAAP,IAAAC,GAAAO,eAAA,qBACAD,EACA,0EAGA,QAAAE,KAGA,UAAAT,IAAAC,GAAAS,gBAFA,+FAIA,QAAAC,GAAAP,GACA,UAAAJ,IAAAC,GAAAW,aAAA,4CAAAR,EAAA,MAEA,QAAAS,KACA,UAAAb,IAAAC,GAAAa,qBAAA,4DAWA,QAAAC,KACA,UAAAf,IAAAC,GAAAe,SAAA,sCAKA,QAAAC,GAAAC,GACA,UAAAlB,IAAAC,GAAAkB,YAAA,gBAAAD,EAAA,MAEA,QAAAE,GAAAb,GACA,UAAAP,IAAAC,GAAAoB,uBAAA,2BAAAd,EAAA,MAQA,QAAAe,KACA,UAAAtB,IAAAC,GAAAsB,kBAAA,0DAEA,QAAAC,KACA,UAAAxB,IAAAC,GAAAwB,uBAAA,wEAEA,QAAAC,KACA,UAAA1B,IAAAC,GAAA0B,gBAAA,mDAEA,QAAAC,GAAAC,EAAAC,EAAAC,GACA,UAAA/B,IAAAC,GAAA+B,iBAAA,wBAAAF,EAAA,cAAAD,EAAA,KAAAE,GAEA,QAAAE,GAAAC,EAAAC,EAAAL,EAAAM,GAC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AAA8Q,IAEAtQ,YAAA,EACAC,cAAA,IAEAmQ,KAMAG,GAAA,WACA,QAAAG,GAAApF,GACA9L,KAAA2N,GAAA7B,EAUA,MAJAoF,GAAAjiB,UAAAid,OAAA,WAEA,MADAlM,MAAA2N,GAAA9F,EAAAwG,YACAze,MAAA8G,KAEAwa,If7IAppB,GAAA,gBAAAoX,EAyBA,IAAAS,IAAA,SAiBAT,IAAAb,GAAA,YnBmoHG,MACO,MAAMrO,GACN,KAAU4F,OACR","file":"firebase-storage.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([2],{\n\n/***/ 122:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(123);\n\n\n/***/ }),\n\n/***/ 123:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/constants.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nvar apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nvar apiUploadBaseUrl = '/v0';\nfunction setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nvar configOption = 'storageBucket';\n/**\n * 1 minute\n */\nvar shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nvar minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/error.js\n/**\n * Copyright 2017 Google Inc.\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\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\n\nvar errors = {};\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nfunction prependCode(code) {\n return 'storage/' + code;\n}\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nfunction bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nfunction projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nfunction invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nfunction error_canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nfunction invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nfunction noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/string.js\n/**\n * Copyright 2017 Google Inc.\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\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw unknown();\n}\nfunction utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nfunction percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar string_DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nfunction dataURLBytes_(string) {\n var parts = new string_DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nfunction dataURLContentType_(string) {\n var parts = new string_DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/taskenums.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/object.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/promise_external.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nfunction make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nfunction promise_external_resolve(value) {\n return Promise.resolve(value);\n}\nfunction promise_external_reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/type.js\n/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nfunction isDef(p) {\n return p != null;\n}\nfunction isJustDef(p) {\n return p !== void 0;\n}\nfunction isFunction(p) {\n return typeof p === 'function';\n}\nfunction isObject(p) {\n return typeof p === 'object';\n}\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio.js\n/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nvar ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio_network.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar xhrio_network_NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\n\n\n//# sourceMappingURL=xhrio_network.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhriopool.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Factory-like class for creating XhrIo instances.\n */\nvar xhriopool_XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new xhrio_network_NetworkXhrIo();\n };\n return XhrIoPool;\n}());\n\n\n//# sourceMappingURL=xhriopool.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/json.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nfunction jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/location.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\n/**\n * @struct\n */\nvar location_Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\n\n\n//# sourceMappingURL=location.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/path.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nfunction path_parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nfunction child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/url.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/metadata.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\n\nvar mappings_ = null;\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new location_Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/args.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n }\n else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar args_ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction metadataSpec(opt_optional) {\n return new args_ArgSpec(metadataValidator, opt_optional);\n}\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/fs.js\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nfunction getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/blob.js\n/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\n\n\n\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar blob_FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\n\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/array.js\n/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nfunction array_contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nfunction array_clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestinfo.js\nvar RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\n\n\n//# sourceMappingURL=requestinfo.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requests.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = blob_FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array_contains(allowed, status));\n return status;\n}\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nvar resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/observer.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * @struct\n */\nvar observer_Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) ||\n isDef(opt_error) ||\n isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\n\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/tasksnapshot.js\nvar UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\n\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/async.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nfunction async_async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promise_external_resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/task.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar task_UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = error_canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) ||\n isJustDef(p['error']) ||\n isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n var observer = new observer_Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n var typeOnly = !(isJustDef(nextOrObserver) ||\n isJustDef(error) ||\n isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = array_clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async_async(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async_async(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async_async(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async_async(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\n\n\n//# sourceMappingURL=task.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/reference.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar reference_Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof location_Location) {\n this.location = location;\n }\n else {\n this.location = location_Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path_parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new location_Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n validate('putString', [\n stringSpec(),\n stringSpec(formatValidator, true),\n metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (isDef(url)) {\n return url;\n }\n else {\n throw noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n return Reference;\n}());\n\n\n//# sourceMappingURL=reference.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/failrequest.js\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar failrequest_FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promise_external_reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\n\n\n//# sourceMappingURL=failrequest.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestmap.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * @struct\n */\nvar requestmap_RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\n\n\n//# sourceMappingURL=requestmap.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/authwrapper.js\n\n\n\n\n\n\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar authwrapper_AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new requestmap_RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = location_Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n isDef(this.app_.INTERNAL) &&\n isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promise_external_resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new failrequest_FailRequest(appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\n\n\n//# sourceMappingURL=authwrapper.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/backoff.js\n/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nfunction stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/request.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\n\n\n\n\n\n\n\n\n/**\n * @struct\n * @template T\n */\nvar request_NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array_contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? appDeleted()\n : error_canceled();\n reject(err);\n }\n else {\n var err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array_contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array_contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nfunction addVersionHeader_(headers) {\n var number = typeof esm[\"default\"] !== 'undefined' ? esm[\"default\"].SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new request_NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/service.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar service_Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new reference_Reference(authWrapper, loc);\n }\n this.authWrapper_ = new authwrapper_AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = location_Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new location_Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new service_ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n validate('ref', [stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new reference_Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n location_Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new reference_Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\n\n/**\n * @struct\n */\nvar service_ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return promise_external_resolve(undefined);\n };\n return ServiceInternals;\n}());\n\n\n//# sourceMappingURL=service.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerStorage\"] = registerStorage;\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new service_Service(app, new xhriopool_XhrIoPool(), opt_url);\n}\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: service_Service,\n Reference: reference_Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[122]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-storage.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-storage.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/storage');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./storage/index.js\n// module id = 122\n// module chunks = 2","/**\n * Copyright 2017 Google Inc.\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 */\nimport { configOption } from './constants';\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\nexport { FirebaseStorageError };\nexport var errors = {};\nexport var Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nexport function prependCode(code) {\n return 'storage/' + code;\n}\nexport function unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nexport function objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nexport function bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nexport function projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nexport function quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nexport function unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nexport function unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nexport function retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nexport function invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nexport function canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nexport function invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nexport function invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nexport function invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nexport function noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nexport function cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nexport function serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nexport function noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nexport function invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nexport function invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nexport function appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nexport var StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nexport function formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\nexport { StringData };\nexport function dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw errorsExports.unknown();\n}\nexport function utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nexport function percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nexport function base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nexport function dataURLBytes_(string) {\n var parts = new DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nexport function dataURLContentType_(string) {\n var parts = new DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/string.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport var TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nexport var InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nexport var TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nexport function taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/taskenums.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nexport function contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nexport function forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nexport function clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/object.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nexport function make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nexport function resolve(value) {\n return Promise.resolve(value);\n}\nexport function reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/promise_external.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef(p) {\n return p != null;\n}\nexport function isJustDef(p) {\n return p !== void 0;\n}\nexport function isFunction(p) {\n return typeof p === 'function';\n}\nexport function isObject(p) {\n return typeof p === 'object';\n}\nexport function isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nexport function isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nexport function isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nexport function isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nexport function isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nexport function isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/type.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/json.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nexport function child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport * as constants from './constants';\nimport * as object from './object';\nexport function makeNormalUrl(urlPart) {\n return constants.domainBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeDownloadUrl(urlPart) {\n return constants.downloadBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeUploadUrl(urlPart) {\n return constants.domainBase + constants.apiUploadBaseUrl + urlPart;\n}\nexport function makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n object.forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/url.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nexport function noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\nexport { Mapping };\nvar mappings_ = null;\nexport function xformPath(fullPath) {\n var valid = type.isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return path.lastComponent(fullPath);\n }\n}\nexport function getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (type.isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = type.isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = UrlUtils.makeDownloadUrl(urlPart);\n var queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nexport function addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nexport function fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nexport function fromResourceString(authWrapper, resourceString, mappings) {\n var obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nexport function toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nexport function metadataValidator(p) {\n var validType = p && type.isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/metadata.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as type from './type';\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n }\n else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\nexport { ArgSpec };\nexport function and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nexport function stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function metadataSpec(opt_optional) {\n return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);\n}\nexport function nonNegativeNumberSpec() {\n function validator(p) {\n var valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/args.js\n// module id = null\n// module chunks = ","import * as type from './type';\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (type.isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/fs.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nexport function contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nexport function clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nexport function remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/array.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as array from './array';\nimport { FbsBlob } from './blob';\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as object from './object';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn) {\n if (!cndn) {\n throw errorsExports.unknown();\n }\n}\nexport function metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = MetadataUtils.fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nexport function sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = errorsExports.unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = errorsExports.quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = errorsExports.unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = errorsExports.objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nexport function metadataForUpload_(location, blob, opt_metadata) {\n var metadata = object.clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nexport function multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = MetadataUtils.toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\nexport { ResumableUploadStatus };\nexport function checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array.contains(allowed, status));\n return status;\n}\nexport function createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport var resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw errorsExports.serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requests.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\nimport * as promiseimpl from './promise_external';\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promiseimpl.resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/async.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\nimport firebase from '@firebase/app';\nimport * as array from './array';\nimport * as backoff from './backoff';\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport * as XhrIoExports from './xhrio';\n/**\n * @struct\n * @template T\n */\nvar NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = promiseimpl.make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array.contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = errorsExports.unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? errorsExports.appDeleted()\n : errorsExports.canceled();\n reject(err);\n }\n else {\n var err = errorsExports.retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array.contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array.contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\nexport { RequestEndStatus };\nexport function addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nexport function addVersionHeader_(headers) {\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nexport function makeRequest(requestInfo, authToken, pool) {\n var queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = object.clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/request.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent } from './src/implementation/taskenums';\nimport { TaskState } from './src/implementation/taskenums';\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new Service(app, new XhrIoPool(), opt_url);\n}\nexport function registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nexport var domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nexport var downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nexport var apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nexport var apiUploadBaseUrl = '/v0';\nexport function setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nexport var configOption = 'storageBucket';\n/**\n * 1 minute\n */\nexport var shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nexport var defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nexport var defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport var minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/constants.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as XhrIoExports from './xhrio';\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = XhrIoExports.ErrorCode.NO_ERROR;\n this.sendPromise_ = promiseimpl.make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(opt_headers)) {\n var headers = opt_headers;\n object.forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (type.isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\nexport { NetworkXhrIo };\n\n//# sourceMappingURL=xhrio_network.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio_network.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { NetworkXhrIo } from './xhrio_network';\n/**\n * Factory-like class for creating XhrIo instances.\n */\nvar XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new NetworkXhrIo();\n };\n return XhrIoPool;\n}());\nexport { XhrIoPool };\n\n//# sourceMappingURL=xhriopool.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhriopool.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\n/**\n * @struct\n */\nvar Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\nexport { Location };\n\n//# sourceMappingURL=location.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/location.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport * as string from './string';\nimport { StringFormat } from './string';\nimport * as type from './type';\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (type.isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (type.isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (type.isString(val)) {\n return string.dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\nexport { FbsBlob };\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/blob.js\n// module id = null\n// module chunks = ","var RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\nexport { RequestInfo };\n\n//# sourceMappingURL=requestinfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestinfo.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * @struct\n */\nvar Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = type.isFunction(nextOrObserver) ||\n type.isDef(opt_error) ||\n type.isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\nexport { Observer };\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/observer.js\n// module id = null\n// module chunks = ","var UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\nexport { UploadTaskSnapshot };\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/tasksnapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\nimport { InternalTaskState } from './implementation/taskenums';\nimport { Observer } from './implementation/observer';\nimport { TaskEvent, TaskState } from './implementation/taskenums';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport * as fbsArgs from './implementation/args';\nimport * as fbsArray from './implementation/array';\nimport { async as fbsAsync } from './implementation/async';\nimport * as errors from './implementation/error';\nimport * as fbsPromiseimpl from './implementation/promise_external';\nimport * as fbsRequests from './implementation/requests';\nimport * as fbsTaskEnums from './implementation/taskenums';\nimport * as typeUtils from './implementation/type';\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = fbsPromiseimpl.make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new fbsRequests.ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = errors.canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = fbsArgs.nullFunctionSpec(true).validator;\n var observerValidator = fbsArgs.looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n fbsArgs.stringSpec(typeValidator),\n fbsArgs.looseObjectSpec(nextOrObserverValidator, true),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n fbsArgs.validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n fbsArgs.validate('on', specs, arguments);\n }\n var observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n fbsArgs.looseObjectSpec(binderNextOrObserverValidator),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n var typeOnly = !(typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n fbsArray.remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = fbsArray.clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n fbsAsync(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n fbsArgs.validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n fbsArgs.validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n fbsArgs.validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\nexport { UploadTask };\n\n//# sourceMappingURL=task.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/task.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport * as args from './implementation/args';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as object from './implementation/object';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport * as fbsString from './implementation/string';\nimport { StringFormat } from './implementation/string';\nimport * as type from './implementation/type';\nimport { UploadTask } from './task';\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof Location) {\n this.location = location;\n }\n else {\n this.location = Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n args.validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return metadata.getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n args.validate('child', [args.stringSpec()], arguments);\n var newPath = path.child(this.location.path, childPath);\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return path.lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n args.validate('put', [args.uploadDataSpec(), args.metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n args.validate('putString', [\n args.stringSpec(),\n args.stringSpec(fbsString.formatValidator, true),\n args.metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = fbsString.dataFromString(format, string);\n var metadata = object.clone(opt_metadata);\n if (!type.isDef(metadata['contentType']) && type.isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n args.validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n args.validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n args.validate('updateMetadata', [args.metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n args.validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (type.isDef(url)) {\n return url;\n }\n else {\n throw errorsExports.noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n };\n return Reference;\n}());\nexport { Reference };\n\n//# sourceMappingURL=reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/reference.js\n// module id = null\n// module chunks = ","import * as promiseimpl from './promise_external';\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promiseimpl.reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\nexport { FailRequest };\n\n//# sourceMappingURL=failrequest.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/failrequest.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as object from './object';\nimport * as constants from './constants';\n/**\n * @struct\n */\nvar RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = constants.minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n object.forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\nexport { RequestMap };\n\n//# sourceMappingURL=requestmap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestmap.js\n// module id = null\n// module chunks = ","import * as constants from './constants';\nimport * as errorsExports from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport * as promiseimpl from './promise_external';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = constants.defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[constants.configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n type.isDef(this.app_.INTERNAL) &&\n type.isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promiseimpl.resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new FailRequest(errorsExports.appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\nexport { AuthWrapper };\n\n//# sourceMappingURL=authwrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/authwrapper.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as fbsPromiseImpl from './implementation/promise_external';\nimport * as RequestExports from './implementation/request';\nimport { Reference } from './reference';\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(app, maker, RequestExports.makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n args.validate('setMaxUploadRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n args.validate('setMaxOperationRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\nexport { Service };\n/**\n * @struct\n */\nvar ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return fbsPromiseImpl.resolve(undefined);\n };\n return ServiceInternals;\n}());\nexport { ServiceInternals };\n\n//# sourceMappingURL=service.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/service.js\n// module id = null\n// module chunks = "],"sourceRoot":""} \ No newline at end of file diff --git a/lib/firebase/firebase.d.ts b/lib/firebase/firebase.d.ts index ea723351..c964087a 100644 --- a/lib/firebase/firebase.d.ts +++ b/lib/firebase/firebase.d.ts @@ -154,12 +154,18 @@ declare namespace firebase.auth { applyActionCode(code: string): Promise; checkActionCode(code: string): Promise; confirmPasswordReset(code: string, newPassword: string): Promise; + createUserAndRetrieveDataWithEmailAndPassword( + email: string, + password: string + ): Promise; createUserWithEmailAndPassword( email: string, password: string ): Promise; currentUser: firebase.User | null; fetchProvidersForEmail(email: string): Promise; + fetchSignInMethodsForEmail(email: string): Promise; + isSignInWithEmailLink(emailLink: string): boolean; getRedirectResult(): Promise; languageCode: string | null; onAuthStateChanged( @@ -176,6 +182,10 @@ declare namespace firebase.auth { error?: (a: firebase.auth.Error) => any, completed?: firebase.Unsubscribe ): firebase.Unsubscribe; + sendSignInLinkToEmail( + email: string, + actionCodeSettings: firebase.auth.ActionCodeSettings + ): Promise; sendPasswordResetEmail( email: string, actionCodeSettings?: firebase.auth.ActionCodeSettings | null @@ -185,15 +195,22 @@ declare namespace firebase.auth { credential: firebase.auth.AuthCredential ): Promise; signInAnonymously(): Promise; + signInAnonymouslyAndRetrieveData(): Promise; signInWithCredential( credential: firebase.auth.AuthCredential ): Promise; signInWithCustomToken(token: string): Promise; + signInAndRetrieveDataWithCustomToken(token: string): Promise; signInWithEmailAndPassword(email: string, password: string): Promise; + signInAndRetrieveDataWithEmailAndPassword( + email: string, + password: string + ): Promise; signInWithPhoneNumber( phoneNumber: string, applicationVerifier: firebase.auth.ApplicationVerifier ): Promise; + signInWithEmailLink(email: string, emailLink?: string): Promise; signInWithPopup(provider: firebase.auth.AuthProvider): Promise; signInWithRedirect(provider: firebase.auth.AuthProvider): Promise; signOut(): Promise; @@ -203,6 +220,7 @@ declare namespace firebase.auth { interface AuthCredential { providerId: string; + signInMethod: string; } interface AuthProvider { @@ -216,10 +234,16 @@ declare namespace firebase.auth { class EmailAuthProvider extends EmailAuthProvider_Instance { static PROVIDER_ID: string; + static EMAIL_PASSWORD_SIGN_IN_METHOD: string; + static EMAIL_LINK_SIGN_IN_METHOD: string; static credential( email: string, password: string ): firebase.auth.AuthCredential; + static credentialWithLink( + email: string, + emailLink: string + ): firebase.auth.AuthCredential; } class EmailAuthProvider_Instance implements firebase.auth.AuthProvider { providerId: string; @@ -232,6 +256,7 @@ declare namespace firebase.auth { class FacebookAuthProvider extends FacebookAuthProvider_Instance { static PROVIDER_ID: string; + static FACEBOOK_SIGN_IN_METHOD: string; static credential(token: string): firebase.auth.AuthCredential; } class FacebookAuthProvider_Instance implements firebase.auth.AuthProvider { @@ -244,6 +269,7 @@ declare namespace firebase.auth { class GithubAuthProvider extends GithubAuthProvider_Instance { static PROVIDER_ID: string; + static GITHUB_SIGN_IN_METHOD: string; static credential(token: string): firebase.auth.AuthCredential; } class GithubAuthProvider_Instance implements firebase.auth.AuthProvider { @@ -256,6 +282,7 @@ declare namespace firebase.auth { class GoogleAuthProvider extends GoogleAuthProvider_Instance { static PROVIDER_ID: string; + static GOOGLE_SIGN_IN_METHOD: string; static credential( idToken?: string | null, accessToken?: string | null @@ -271,6 +298,7 @@ declare namespace firebase.auth { class PhoneAuthProvider extends PhoneAuthProvider_Instance { static PROVIDER_ID: string; + static PHONE_SIGN_IN_METHOD: string; static credential( verificationId: string, verificationCode: string @@ -301,6 +329,7 @@ declare namespace firebase.auth { class TwitterAuthProvider extends TwitterAuthProvider_Instance { static PROVIDER_ID: string; + static TWITTER_SIGN_IN_METHOD: string; static credential( token: string, secret: string @@ -346,9 +375,9 @@ declare namespace firebase.database { hasChildren(): boolean; key: string | null; numChildren(): number; + val(): any; ref: firebase.database.Reference; toJSON(): Object | null; - val(): any; } interface Database { @@ -474,6 +503,7 @@ declare namespace firebase.messaging { requestPermission(): Promise | null; setBackgroundMessageHandler(callback: (a: Object) => any): any; useServiceWorker(registration: any): any; + usePublicVapidKey(b64PublicKey: string): void; } } @@ -617,7 +647,7 @@ declare namespace firebase.firestore { export type LogLevel = 'debug' | 'error' | 'silent'; - function setLogLevel(logLevel: LogLevel): void; + export function setLogLevel(logLevel: LogLevel): void; /** * `Firestore` represents a Firestore Database and is the entry point for all @@ -625,7 +655,6 @@ declare namespace firebase.firestore { */ export class Firestore { private constructor(); - /** * Specifies custom settings to be used to configure the `Firestore` * instance. Must be set before invoking any other methods. @@ -698,10 +727,28 @@ declare namespace firebase.firestore { batch(): WriteBatch; /** - * The `firebase.app.App` associated with this `Firestore` instance. + * The `FirebaseApp` associated with this `Firestore` instance. */ app: firebase.app.App; + /** + * Re-enables use of the network for this Firestore instance after a prior + * call to disableNetwork(). + * + * @return A promise that is resolved once the network has been enabled. + */ + enableNetwork(): Promise; + + /** + * Disables network usage for this instance. It can be re-enabled via + * enableNetwork(). While the network is disabled, any snapshot listeners or + * get() calls will return results from cache, and any write operations will + * be queued until the network is restored. + * + * @return A promise that is resolved once the network has been disabled. + */ + disableNetwork(): Promise; + INTERNAL: { delete: () => Promise }; } @@ -723,6 +770,14 @@ declare namespace firebase.firestore { readonly latitude: number; readonly longitude: number; + + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other The `GeoPoint` to compare against. + * @return true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; } /** @@ -751,6 +806,14 @@ declare namespace firebase.firestore { * Returns the bytes of this Blob in a new Uint8Array. */ public toUint8Array(): Uint8Array; + + /** + * Returns true if this `Blob` is equal to the provided one. + * + * @param other The `Blob` to compare against. + * @return true if this `Blob` is equal to the provided one. + */ + isEqual(other: Blob): boolean; } /** @@ -1092,6 +1155,29 @@ declare namespace firebase.firestore { ): () => void; } + /** + * Options that configure how data is retrieved from a `DocumentSnapshot` + * (e.g. the desired behavior for server timestamps that have not yet been set + * to their final value). + */ + export interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; + } + /** Metadata about a snapshot, describing the state of the snapshot. */ export interface SnapshotMetadata { /** @@ -1112,15 +1198,27 @@ declare namespace firebase.firestore { * the client has received up-to-date data from the backend. */ readonly fromCache: boolean; + + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other The `SnapshotMetadata` to compare against. + * @return true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; } /** * A `DocumentSnapshot` contains data read from a document in your Firestore * database. The data can be extracted with `.data()` or `.get()` to * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists` property to + * explicitly verify a document's existence. */ export class DocumentSnapshot { - private constructor(); + protected constructor(); /** True if the document exists. */ readonly exists: boolean; @@ -1137,20 +1235,75 @@ declare namespace firebase.firestore { readonly metadata: SnapshotMetadata; /** - * Retrieves all fields in the document as an Object. + * Retrieves all fields in the document as an Object. Returns 'undefined' if + * the document doesn't exist. * - * @return An Object containing all fields in the document. + * By default, `FieldValue.serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options An options object to configure how data is retrieved from + * the snapshot (e.g. the desired behavior for server timestamps that have + * not yet been set to their final value). + * @return An Object containing all fields in the document or 'undefined' if + * the document doesn't exist. */ - data(): DocumentData; + data(options?: SnapshotOptions): DocumentData | undefined; /** - * Retrieves the field specified by `fieldPath`. + * Retrieves the field specified by `fieldPath`. Returns 'undefined' if the + * document or field doesn't exist. + * + * By default, a `FieldValue.serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. * * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @param options An options object to configure how the field is retrieved + * from the snapshot (e.g. the desired behavior for server timestamps that have + * not yet been set to their final value). * @return The data at the specified field location or undefined if no such * field exists in the document. */ - get(fieldPath: string | FieldPath): any; + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + + /** + * Returns true if this `DocumentSnapshot` is equal to the provided one. + * + * @param other The `DocumentSnapshot` to compare against. + * @return true if this `DocumentSnapshot` is equal to the provided one. + */ + isEqual(other: DocumentSnapshot): boolean; + } + + /** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ + export class QueryDocumentSnapshot extends DocumentSnapshot { + private constructor(); + + /** + * Retrieves all fields in the document as an Object. + * + * By default, `FieldValue.serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options An options object to configure how data is retrieved from + * the snapshot (e.g. the desired behavior for server timestamps that have + * not yet been set to their final value). + * @return An Object containing all fields in the document. + */ + data(options?: SnapshotOptions): DocumentData; } /** @@ -1410,7 +1563,7 @@ declare namespace firebase.firestore { readonly docChanges: DocumentChange[]; /** An array of all the documents in the QuerySnapshot. */ - readonly docs: DocumentSnapshot[]; + readonly docs: QueryDocumentSnapshot[]; /** The number of documents in the QuerySnapshot. */ readonly size: number; @@ -1421,11 +1574,22 @@ declare namespace firebase.firestore { /** * Enumerates all of the documents in the QuerySnapshot. * - * @param callback A callback to be called with a `DocumentSnapshot` for + * @param callback A callback to be called with a `QueryDocumentSnapshot` for * each document in the snapshot. * @param thisArg The `this` binding for the callback. */ - forEach(callback: (result: DocumentSnapshot) => void, thisArg?: any): void; + forEach( + callback: (result: QueryDocumentSnapshot) => void, + thisArg?: any + ): void; + + /** + * Returns true if this `QuerySnapshot` is equal to the provided one. + * + * @param other The `QuerySnapshot` to compare against. + * @return true if this `QuerySnapshot` is equal to the provided one. + */ + isEqual(other: QuerySnapshot): boolean; } /** @@ -1442,7 +1606,7 @@ declare namespace firebase.firestore { readonly type: DocumentChangeType; /** The document affected by this change. */ - readonly doc: DocumentSnapshot; + readonly doc: QueryDocumentSnapshot; /** * The index of the changed document in the result set immediately prior to @@ -1502,6 +1666,14 @@ declare namespace firebase.firestore { * newly created document after it has been written to the backend. */ add(data: DocumentData): Promise; + + /** + * Returns true if this `CollectionReference` is equal to the provided one. + * + * @param other The `CollectionReference` to compare against. + * @return true if this `CollectionReference` is equal to the provided one. + */ + isEqual(other: CollectionReference): boolean; } /** @@ -1521,6 +1693,14 @@ declare namespace firebase.firestore { * Returns a sentinel for use with update() to mark a field for deletion. */ static delete(): FieldValue; + + /** + * Returns true if this `FieldValue` is equal to the provided one. + * + * @param other The `FieldValue` to compare against. + * @return true if this `FieldValue` is equal to the provided one. + */ + isEqual(other: FieldValue): boolean; } /** @@ -1542,6 +1722,14 @@ declare namespace firebase.firestore { * It can be used in queries to sort or filter by the document ID. */ static documentId(): FieldPath; + + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other The `FieldPath` to compare against. + * @return true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; } /** @@ -1611,4 +1799,6 @@ declare namespace firebase.firestore { } } -export = firebase; +declare module 'firebase' { + export = firebase; +} diff --git a/lib/firebase/firebase.js b/lib/firebase/firebase.js index 529de8e1..57b8bc29 100644 --- a/lib/firebase/firebase.js +++ b/lib/firebase/firebase.js @@ -1,36 +1,50 @@ /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -var firebase=function(){var e=void 0===e?self:e;return function(t){function r(e){if(o[e])return o[e].exports;var n=o[e]={i:e,l:!1,exports:{}};return t[e].call(n.exports,n,n.exports,r),n.l=!0,n.exports}var n=e.webpackJsonpFirebase;e.webpackJsonpFirebase=function(e,o,a){for(var c,s,u,f=0,l=[];f1)for(var r=1;r255;)t[r++]=255&o,o>>=8;t[r++]=o}return t},o=function(e){if(e.length<8192)return String.fromCharCode.apply(null,e);for(var t="",r=0;r>2,l=(3&i)<<4|c>>4,h=(15&c)<<2|u>>6,p=63&u;s||(p=64,a||(h=64)),n.push(r[f],r[l],r[h],r[p])}return n.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):o(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.O();for(var r=t?this.g:this.b,n=[],o=0;o>4;if(n.push(h),64!=u){var p=c<<4&240|u>>2;if(n.push(p),64!=l){var d=u<<6&192|l;n.push(d)}}}return n},O:function(){if(!this.y){this.y={},this.b={},this._={},this.g={};for(var e=0;e=this.ENCODED_VALS_BASE.length&&(this.b[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.g[this.ENCODED_VALS.charAt(e)]=e)}}},t.base64Encode=function(e){var r=n(e);return t.base64.encodeByteArray(r,!0)},t.base64Decode=function(e){try{return t.base64.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}},function(e,t,r){"use strict";function n(e){return JSON.parse(e)}function o(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.jsonEval=n,t.stringify=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.safeGet=function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]},t.forEach=function(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])},t.extend=function(e,r){return t.forEach(r,function(t,r){e[t]=r}),e},t.clone=function(e){return t.extend({},e)},t.isNonNullObject=function(e){return"object"==typeof e&&null!==e},t.isEmpty=function(e){for(var t in e)return!1;return!0},t.getCount=function(e){var t=0;for(var r in e)t++;return t},t.map=function(e,t,r){var n={};for(var o in e)n[o]=t.call(r,e[o],o,e);return n},t.findKey=function(e,t,r){for(var n in e)if(t.call(r,e[n],n,e))return n},t.findValue=function(e,r,n){var o=t.findKey(e,r,n);return o&&e[o]},t.getAnyKey=function(e){for(var t in e)return t},t.getValues=function(e){var t=[],r=0;for(var n in e)t[r++]=e[n];return t},t.every=function(e,t){for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&!t(r,e[r]))return!1;return!0}},,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,r){r(58),e.exports=r(6).default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(59),o=(r.n(n),r(63)),i=(r.n(o),r(64));r.n(i)},function(t,r,n){(function(t){var r=function(){if(void 0!==t)return t;if(void 0!==e)return e;if("undefined"!=typeof self)return self;throw Error("unable to locate global object")}();"undefined"==typeof Promise&&(r.Promise=Promise=n(60))}).call(r,n(19))},function(e,t,r){(function(t){!function(r){function n(){}function o(e,t){return function(){e.apply(t,arguments)}}function i(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this.T=[],l(e,this)}function a(e,t){for(;3===e._state;)e=e._value;if(0===e._state)return void e.T.push(t);e._handled=!0,i.A(function(){var r=1===e._state?t.onFulfilled:t.onRejected;if(null===r)return void(1===e._state?c:s)(t.promise,e._value);var n;try{n=r(e._value)}catch(e){return void s(t.promise,e)}c(t.promise,n)})}function c(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if(t instanceof i)return e._state=3,e._value=t,void u(e);if("function"==typeof r)return void l(o(r,t),e)}e._state=1,e._value=t,u(e)}catch(t){s(e,t)}}function s(e,t){e._state=2,e._value=t,u(e)}function u(e){2===e._state&&0===e.T.length&&i.A(function(){e._handled||i.j(e._value)});for(var t=0,r=e.T.length;t=0&&(e.N=setTimeout(function(){e.M&&e.M()},t))},n(62),r.setImmediate=setImmediate,r.clearImmediate=clearImmediate},function(e,t,r){(function(e,t){!function(e,r){"use strict";function n(e){"function"!=typeof e&&(e=Function(""+e));for(var t=Array(arguments.length-1),r=0;r>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o"}),r=this.serviceName+": "+r+" ("+o+").";var i=new a(o,r);for(var c in t)t.hasOwnProperty(c)&&"_"!==c.slice(-1)&&(i[c]=t[c]);return i},e}();t.ErrorFactory=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(29),o=r(30);t.decode=function(e){var t={},r={},i={},a="";try{var c=e.split(".");t=o.jsonEval(n.base64Decode(c[0])||""),r=o.jsonEval(n.base64Decode(c[1])||""),a=c[2],i=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:i,signature:a}},t.isValidTimestamp=function(e){var r,n,o=t.decode(e).claims,i=Math.floor((new Date).getTime()/1e3);return"object"==typeof o&&(o.hasOwnProperty("nbf")?r=o.nbf:o.hasOwnProperty("iat")&&(r=o.iat),n=o.hasOwnProperty("exp")?o.exp:r+86400),i&&r&&n&&i>=r&&i<=n},t.issuedAtTime=function(e){var r=t.decode(e).claims;return"object"==typeof r&&r.hasOwnProperty("iat")?r.iat:null},t.isValidFormat=function(e){var r=t.decode(e),n=r.claims;return!!r.signature&&!!n&&"object"==typeof n&&n.hasOwnProperty("iat")},t.isAdmin=function(e){var r=t.decode(e).claims;return"object"==typeof r&&!0===r.admin}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(31);t.querystring=function(e){var t=[];return n.forEach(e,function(e,r){Array.isArray(r)?r.forEach(function(r){t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}):t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}),t.length?"&"+t.join("&"):""},t.querystringDecode=function(e){var t={};return e.replace(/^\?/,"").split("&").forEach(function(e){if(e){var r=e.split("=");t[r[0]]=r[1]}}),t}},function(e,t,r){"use strict";var n=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(t,"__esModule",{value:!0});var o=r(72),i=function(e){function t(){var t=e.call(this)||this;t.D=[],t.I=[],t.x=[],t.F=[],t.L=0,t.R=0,t.blockSize=64,t.F[0]=128;for(var r=1;r>>31)}for(var i,a,c=this.D[0],s=this.D[1],u=this.D[2],f=this.D[3],l=this.D[4],n=0;n<80;n++){n<40?n<20?(i=f^s&(u^f),a=1518500249):(i=s^u^f,a=1859775393):n<60?(i=s&u|f&(s|u),a=2400959708):(i=s^u^f,a=3395469782);var o=(c<<5|c>>>27)+i+l+a+r[n]&4294967295;l=f,f=u,u=4294967295&(s<<30|s>>>2),s=c,c=o}this.D[0]=this.D[0]+c&4294967295,this.D[1]=this.D[1]+s&4294967295,this.D[2]=this.D[2]+u&4294967295,this.D[3]=this.D[3]+f&4294967295,this.D[4]=this.D[4]+l&4294967295},t.prototype.update=function(e,t){if(null!=e){void 0===t&&(t=e.length);for(var r=t-this.blockSize,n=0,o=this.I,i=this.L;n=56;r--)this.I[r]=255&t,t/=256;this.B(this.I);for(var n=0,r=0;r<5;r++)for(var o=24;o>=0;o-=8)e[n]=this.D[r]>>o&255,++n;return e},t}(o.Hash);t.Sha1=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this.blockSize=-1}return e}();t.Hash=n},function(e,t,r){"use strict";function n(e,t){var r=new c(e,t);return r.subscribe.bind(r)}function o(e,t){return function(){for(var r=[],n=0;n 4. Need to update it?")}var o=e+" failed: ";return o+=n+" argument "}function o(e,t,r,o){if((!o||r)&&"string"!=typeof r)throw Error(n(e,t,o)+"must be a valid firebase namespace.")}function i(e,t,r,o){if((!o||r)&&"function"!=typeof r)throw Error(n(e,t,o)+"must be a valid function.")}function a(e,t,r,o){if((!o||r)&&("object"!=typeof r||null===r))throw Error(n(e,t,o)+"must be a valid context object.")}Object.defineProperty(t,"__esModule",{value:!0}),t.validateArgCount=function(e,t,r,n){var o;if(nr&&(o=0===r?"none":"no more than "+r),o){var i=e+" failed: Was called with "+n+(1===n?" argument.":" arguments.")+" Expects "+o+".";throw Error(i)}},t.errorPrefix=n,t.validateNamespace=o,t.validateCallback=i,t.validateContextObject=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(28);t.stringToByteArray=function(e){for(var t=[],r=0,o=0;o=55296&&i<=56319){var a=i-55296;o++,n.assert(o>6|192,t[r++]=63&i|128):i<65536?(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t},t.stringLength=function(e){for(var t=0,r=0;r=55296&&n<=56319?(t+=4,r++):t+=3}return t}}])}().default; +var firebase=function(){var e=void 0===e?self:e;return function(t){function r(e){if(o[e])return o[e].exports;var n=o[e]={i:e,l:!1,exports:{}};return t[e].call(n.exports,n,n.exports,r),n.l=!0,n.exports}var n=e.webpackJsonpFirebase;e.webpackJsonpFirebase=function(e,o,a){for(var c,s,u,f=0,l=[];f=0;c--)(o=e[c])&&(a=(i<3?o(a):i>3?o(t,r,a):o(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a}function a(e,t){return function(r,n){t(r,n,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function s(e,t,r,n){return new(r||(r=Promise))(function(o,i){function a(e){try{s(n.next(e))}catch(e){i(e)}}function c(e){try{s(n.throw(e))}catch(e){i(e)}}function s(e){e.done?o(e.value):new r(function(t){t(e.value)}).then(a,c)}s((n=n.apply(e,t||[])).next())})}function u(e,t){function r(e){return function(t){return n([e,t])}}function n(r){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,i&&(a=i[2&r[0]?"return":r[0]?"throw":"next"])&&!(a=a.call(i,r[1])).done)return a;switch(i=0,a&&(r=[0,a.value]),r[0]){case 0:case 1:a=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(a=s.trys,!(a=a.length>0&&a[a.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function h(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a}function p(){for(var e=[],t=0;t1||o(e,t)})})}function o(e,t){try{i(f[e](t))}catch(e){s(l[0][3],e)}}function i(e){e.value instanceof d?Promise.resolve(e.value.v).then(a,c):s(l[0][2],e)}function a(e){o("next",e)}function c(e){o("throw",e)}function s(e,t){e(t),l.shift(),l.length&&o(l[0][0],l[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var u,f=r.apply(e,t||[]),l=[];return u={},n("next"),n("throw"),n("return"),u[Symbol.asyncIterator]=function(){return this},u}function y(e){function t(t,o){e[t]&&(r[t]=function(r){return(n=!n)?{value:d(e[t](r)),done:"return"===t}:o?o(r):r})}var r,n;return r={},t("next"),t("throw",function(e){throw e}),t("return"),r[Symbol.iterator]=function(){return this},r}function b(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator];return t?t.call(e):"function"==typeof l?l(e):e[Symbol.iterator]()}function _(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function m(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function g(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.__extends=n,r.d(t,"__assign",function(){return E}),t.__rest=o,t.__decorate=i,t.__param=a,t.__metadata=c,t.__awaiter=s,t.__generator=u,t.__exportStar=f,t.__values=l,t.__read=h,t.__spread=p,t.__await=d,t.__asyncGenerator=v,t.__asyncDelegator=y,t.__asyncValues=b,t.__makeTemplateObject=_,t.__importStar=m,t.__importDefault=g;/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +var O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},E=Object.assign||function(e){for(var t,r=1,n=arguments.length;r1)for(var r=1;r>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t},o=function(e){for(var t=[],r=0,n=0;r191&&o<224){var i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){var i=e[r++],a=e[r++],c=e[r++],s=((7&o)<<18|(63&i)<<12|(63&a)<<6|63&c)-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{var i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")};t.base64={y:null,b:null,_:null,g:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.O();for(var r=t?this._:this.y,n=[],o=0;o>2,l=(3&i)<<4|c>>4,h=(15&c)<<2|u>>6,p=63&u;s||(p=64,a||(h=64)),n.push(r[f],r[l],r[h],r[p])}return n.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):o(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.O();for(var r=t?this.g:this.b,n=[],o=0;o>4;if(n.push(h),64!=u){var p=c<<4&240|u>>2;if(n.push(p),64!=l){var d=u<<6&192|l;n.push(d)}}}return n},O:function(){if(!this.y){this.y={},this.b={},this._={},this.g={};for(var e=0;e=this.ENCODED_VALS_BASE.length&&(this.b[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.g[this.ENCODED_VALS.charAt(e)]=e)}}},t.base64Encode=function(e){var r=n(e);return t.base64.encodeByteArray(r,!0)},t.base64Decode=function(e){try{return t.base64.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}},function(e,t,r){"use strict";function n(e){return JSON.parse(e)}function o(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.jsonEval=n,t.stringify=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.safeGet=function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]},t.forEach=function(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])},t.extend=function(e,r){return t.forEach(r,function(t,r){e[t]=r}),e},t.clone=function(e){return t.extend({},e)},t.isNonNullObject=function(e){return"object"==typeof e&&null!==e},t.isEmpty=function(e){for(var t in e)return!1;return!0},t.getCount=function(e){var t=0;for(var r in e)t++;return t},t.map=function(e,t,r){var n={};for(var o in e)n[o]=t.call(r,e[o],o,e);return n},t.findKey=function(e,t,r){for(var n in e)if(t.call(r,e[n],n,e))return n},t.findValue=function(e,r,n){var o=t.findKey(e,r,n);return o&&e[o]},t.getAnyKey=function(e){for(var t in e)return t},t.getValues=function(e){var t=[],r=0;for(var n in e)t[r++]=e[n];return t},t.every=function(e,t){for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&!t(r,e[r]))return!1;return!0}},,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,r){r(60),e.exports=r(7).default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(61),o=(r.n(n),r(65)),i=(r.n(o),r(66));r.n(i)},function(t,r,n){(function(t){var r=function(){if(void 0!==t)return t;if(void 0!==e)return e;if("undefined"!=typeof self)return self;throw Error("unable to locate global object")}();"undefined"==typeof Promise&&(r.Promise=Promise=n(62))}).call(r,n(11))},function(e,t,r){"use strict";(function(t){function r(){}function n(e,t){return function(){e.apply(t,arguments)}}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this.T=[],f(e,this)}function i(e,t){for(;3===e._state;)e=e._value;if(0===e._state)return void e.T.push(t);e._handled=!0,o.A(function(){var r=1===e._state?t.onFulfilled:t.onRejected;if(null===r)return void(1===e._state?a:c)(t.promise,e._value);var n;try{n=r(e._value)}catch(e){return void c(t.promise,e)}a(t.promise,n)})}function a(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if(t instanceof o)return e._state=3,e._value=t,void s(e);if("function"==typeof r)return void f(n(r,t),e)}e._state=1,e._value=t,s(e)}catch(t){c(e,t)}}function c(e,t){e._state=2,e._value=t,s(e)}function s(e){2===e._state&&0===e.T.length&&o.A(function(){e._handled||o.S(e._value)});for(var t=0,r=e.T.length;t=0&&(e.j=setTimeout(function(){e.N&&e.N()},t))},n(64),r.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,r.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(r,n(11))},function(e,t,r){(function(e,t){!function(e,r){"use strict";function n(e){"function"!=typeof e&&(e=Function(""+e));for(var t=Array(arguments.length-1),r=0;r>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o"}),r=this.serviceName+": "+r+" ("+o+").";var i=new a(o,r);for(var c in t)t.hasOwnProperty(c)&&"_"!==c.slice(-1)&&(i[c]=t[c]);return i},e}();t.ErrorFactory=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(31),o=r(32);t.decode=function(e){var t={},r={},i={},a="";try{var c=e.split(".");t=o.jsonEval(n.base64Decode(c[0])||""),r=o.jsonEval(n.base64Decode(c[1])||""),a=c[2],i=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:i,signature:a}},t.isValidTimestamp=function(e){var r,n,o=t.decode(e).claims,i=Math.floor((new Date).getTime()/1e3);return"object"==typeof o&&(o.hasOwnProperty("nbf")?r=o.nbf:o.hasOwnProperty("iat")&&(r=o.iat),n=o.hasOwnProperty("exp")?o.exp:r+86400),i&&r&&n&&i>=r&&i<=n},t.issuedAtTime=function(e){var r=t.decode(e).claims;return"object"==typeof r&&r.hasOwnProperty("iat")?r.iat:null},t.isValidFormat=function(e){var r=t.decode(e),n=r.claims;return!!r.signature&&!!n&&"object"==typeof n&&n.hasOwnProperty("iat")},t.isAdmin=function(e){var r=t.decode(e).claims;return"object"==typeof r&&!0===r.admin}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(33);t.querystring=function(e){var t=[];return n.forEach(e,function(e,r){Array.isArray(r)?r.forEach(function(r){t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}):t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}),t.length?"&"+t.join("&"):""},t.querystringDecode=function(e){var t={};return e.replace(/^\?/,"").split("&").forEach(function(e){if(e){var r=e.split("=");t[r[0]]=r[1]}}),t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=r(74),i=function(e){function t(){var t=e.call(this)||this;t.k=[],t.x=[],t.M=[],t.D=[],t.I=0,t.F=0,t.blockSize=64,t.D[0]=128;for(var r=1;r>>31)}for(var i,a,c=this.k[0],s=this.k[1],u=this.k[2],f=this.k[3],l=this.k[4],n=0;n<80;n++){n<40?n<20?(i=f^s&(u^f),a=1518500249):(i=s^u^f,a=1859775393):n<60?(i=s&u|f&(s|u),a=2400959708):(i=s^u^f,a=3395469782);var o=(c<<5|c>>>27)+i+l+a+r[n]&4294967295;l=f,f=u,u=4294967295&(s<<30|s>>>2),s=c,c=o}this.k[0]=this.k[0]+c&4294967295,this.k[1]=this.k[1]+s&4294967295,this.k[2]=this.k[2]+u&4294967295,this.k[3]=this.k[3]+f&4294967295,this.k[4]=this.k[4]+l&4294967295},t.prototype.update=function(e,t){if(null!=e){void 0===t&&(t=e.length);for(var r=t-this.blockSize,n=0,o=this.x,i=this.I;n=56;r--)this.x[r]=255&t,t/=256;this.R(this.x);for(var n=0,r=0;r<5;r++)for(var o=24;o>=0;o-=8)e[n]=this.k[r]>>o&255,++n;return e},t}(o.Hash);t.Sha1=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this.blockSize=-1}return e}();t.Hash=n},function(e,t,r){"use strict";function n(e,t){var r=new c(e,t);return r.subscribe.bind(r)}function o(e,t){return function(){for(var r=[],n=0;n 4. Need to update it?")}var o=e+" failed: ";return o+=n+" argument "}function o(e,t,r,o){if((!o||r)&&"string"!=typeof r)throw Error(n(e,t,o)+"must be a valid firebase namespace.")}function i(e,t,r,o){if((!o||r)&&"function"!=typeof r)throw Error(n(e,t,o)+"must be a valid function.")}function a(e,t,r,o){if((!o||r)&&("object"!=typeof r||null===r))throw Error(n(e,t,o)+"must be a valid context object.")}Object.defineProperty(t,"__esModule",{value:!0}),t.validateArgCount=function(e,t,r,n){var o;if(nr&&(o=0===r?"none":"no more than "+r),o){var i=e+" failed: Was called with "+n+(1===n?" argument.":" arguments.")+" Expects "+o+".";throw Error(i)}},t.errorPrefix=n,t.validateNamespace=o,t.validateCallback=i,t.validateContextObject=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(30);t.stringToByteArray=function(e){for(var t=[],r=0,o=0;o=55296&&i<=56319){var a=i-55296;o++,n.assert(o>6|192,t[r++]=63&i|128):i<65536?(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t},t.stringLength=function(e){for(var t=0,r=0;r=55296&&n<=56319?(t+=4,r++):t+=3}return t}}])}().default; /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -try{webpackJsonpFirebase([4],{76:function(t,n,e){e(77)},77:function(t,n,e){(function(t){(function(){function t(t){return"string"==typeof t}function n(t){return"boolean"==typeof t}function i(){}function r(t){var n=typeof t;if("object"==n){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return n;var e=Object.prototype.toString.call(t);if("[object Window]"==e)return"object";if("[object Array]"==e||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==e||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==n&&void 0===t.call)return"object";return n}function o(t){return null===t}function a(t){return"array"==r(t)}function s(t){var n=r(t);return"array"==n||"object"==n&&"number"==typeof t.length}function u(t){return"function"==r(t)}function c(t){var n=typeof t;return"object"==n&&null!=t||"function"==n}function h(t,n,e){return t.call.apply(t.bind,arguments)}function f(t,n,e){if(!t)throw Error();if(2")&&(t=t.replace(lu,">")),-1!=t.indexOf('"')&&(t=t.replace(pu,""")),-1!=t.indexOf("'")&&(t=t.replace(du,"'")),-1!=t.indexOf("\0")&&(t=t.replace(vu,"�")),t):t}function b(t,n){return-1!=t.indexOf(n)}function w(t,n){return tn?1:0}function y(t,n){n.unshift(t),v.call(this,m.apply(null,n)),n.shift()}function I(t,n){throw new y("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function T(n,e){var i=n.length,r=t(n)?n.split(""):n;for(--i;0<=i;--i)i in r&&e.call(void 0,r[i],i,n)}function k(n){t:{for(var e=ke,i=n.length,r=t(n)?n.split(""):n,o=0;oe?null:t(n)?n.charAt(e):n[e]}function A(t,n){return 0<=bu(t,n)}function E(t,n){n=bu(t,n);var e;return(e=0<=n)&&Array.prototype.splice.call(t,n,1),e}function N(t,n){var e=0;T(t,function(i,r){n.call(void 0,i,r,t)&&1==Array.prototype.splice.call(t,r,1).length&&e++})}function S(t){return Array.prototype.concat.apply([],arguments)}function O(t){var n=t.length;if(0"),s=s.join("")}return s=o.createElement(s),u&&(t(u)?s.className=u:a(u)?s.className=u.join(" "):Lt(s,u)),2i.keyCode||void 0!=i.returnValue)){t:{var r=!1;if(0==i.keyCode)try{i.keyCode=-1;break t}catch(t){r=!0}(r||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],r=n.b;r;r=r.parentNode)i.push(r);for(t=t.type,r=i.length-1;0<=r;r--){n.b=i[r];var o=an(i[r],t,!0,n);e=e&&o}for(r=0;r>4),64!=a&&(n(o<<4&240|a>>2),64!=s&&n(a<<6&192|s))}}function Cn(){if(!Ac){Ac={},Ec={};for(var t=0;65>t;t++)Ac[t]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(t),Ec[Ac[t]]=t,62<=t&&(Ec["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(t)]=t)}}function _n(t,n){this.g=[],this.v=t,this.o=n||null,this.f=this.a=!1,this.c=void 0,this.u=this.w=this.i=!1,this.h=0,this.b=null,this.l=0}function Rn(t,n,e){t.a=!0,t.c=e,t.f=!n,Un(t)}function Dn(t){if(t.a){if(!t.u)throw new Mn;t.u=!1}}function Ln(t,n){xn(t,null,n,void 0)}function xn(t,n,e,i){t.g.push([n,e,i]),t.a&&Un(t)}function jn(t){return Iu(t.g,function(t){return u(t[1])})}function Un(t){if(t.h&&t.a&&jn(t)){var n=t.h,e=Sc[n];e&&(ou.clearTimeout(e.a),delete Sc[n]),t.h=0}t.b&&(t.b.l--,delete t.b),n=t.c;for(var i=e=!1;t.g.length&&!t.i;){var r=t.g.shift(),o=r[0],a=r[1];if(r=r[2],o=t.f?a:o)try{var s=o.call(r||t.o,n);void 0!==s&&(t.f=t.f&&(s==n||s instanceof Error),t.c=n=s),(q(n)||"function"==typeof ou.Promise&&n instanceof ou.Promise)&&(i=!0,t.i=!0)}catch(i){n=i,t.f=!0,jn(t)||(e=!0)}}t.c=n,i&&(s=l(t.m,t,!0),i=l(t.m,t,!1),n instanceof _n?(xn(n,s,i),n.w=!0):n.then(s,i)),e&&(n=new Fn(n),Sc[n.a]=n,t.h=n.a)}function Mn(){v.call(this)}function Vn(){v.call(this)}function Fn(t){this.a=ou.setTimeout(l(this.c,this),0),this.b=t}function Kn(){this.b=-1}function qn(t,n){this.b=-1,this.b=Oc,this.f=ou.Uint8Array?new Uint8Array(this.b):Array(this.b),this.g=this.c=0,this.a=[],this.i=t,this.h=n,this.l=ou.Int32Array?new Int32Array(64):Array(64),Nc||(Nc=ou.Int32Array?new Int32Array(Dc):Dc),this.reset()}function Xn(t){for(var n=t.f,e=t.l,i=0,r=0;rn;n++){r=0|e[n-15],i=0|e[n-2];var o=(0|e[n-16])+((r>>>7|r<<25)^(r>>>18|r<<14)^r>>>3)|0,a=(0|e[n-7])+((i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10)|0;e[n]=o+a|0}i=0|t.a[0],r=0|t.a[1];var s=0|t.a[2],u=0|t.a[3],c=0|t.a[4],h=0|t.a[5],f=0|t.a[6];for(o=0|t.a[7],n=0;64>n;n++){var l=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&r^i&s^r&s)|0;a=c&h^~c&f,o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0,a=a+(0|Nc[n])|0,a=o+(a+(0|e[n])|0)|0,o=f,f=h,h=c,c=u+a|0,u=s,s=r,r=i,i=a+l|0}t.a[0]=t.a[0]+i|0,t.a[1]=t.a[1]+r|0,t.a[2]=t.a[2]+s|0,t.a[3]=t.a[3]+u|0,t.a[4]=t.a[4]+c|0,t.a[5]=t.a[5]+h|0,t.a[6]=t.a[6]+f|0,t.a[7]=t.a[7]+o|0}function Bn(n,e,i){void 0===i&&(i=e.length);var r=0,o=n.c;if(t(e))for(;r=a&&a==(0|a)))throw Error("message must be a byte array");n.f[o++]=a,o==n.b&&(Xn(n),o=0)}}n.c=o,n.g+=i}function Hn(){qn.call(this,8,Lc)}function Wn(n){if(n.P&&"function"==typeof n.P)return n.P();if(t(n))return n.split("");if(s(n)){for(var e=[],i=n.length,r=0;rn)throw Error("Bad port number "+n);t.i=n}else t.i=null}function Qn(t,n,e){n instanceof se?(t.a=n,ve(t.a,t.f)):(e||(n=oe(n,Vc)),t.a=new se(n,0,t.f))}function te(t,n,e){t.a.set(n,e)}function ne(t,n){return t.a.get(n)}function ee(t){return t instanceof Yn?new Yn(t):new Yn(t,void 0)}function ie(t,n){var e=new Yn(null,void 0);return $n(e,"https"),t&&(e.b=t),n&&(e.g=n),e}function re(t,n){return t?n?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function oe(n,e,i){return t(n)?(n=encodeURI(n).replace(e,ae),i&&(n=n.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),n):null}function ae(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function se(t,n,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function ue(t){t.a||(t.a=new kn,t.b=0,t.c&&Jn(t.c,function(n,e){he(t,decodeURIComponent(n.replace(/\+/g," ")),e)}))}function ce(t){var n=Gn(t);if(void 0===n)throw Error("Keys are undefined");var e=new se(null,0,void 0);t=Wn(t);for(var i=0;i2*t.c&&An(t)))}function le(t,n){return ue(t),n=de(t,n),En(t.a.b,n)}function pe(t,n,e){fe(t,n),0t||Su&&xu&&!(9',t=Rt(t),a.document.write(_t(t)),a.document.close())):a=t.open(St(n),e,a),a)try{a.focus()}catch(t){}return a}function Je(t){return new Z(function(n){function e(){gn(2e3).then(function(){if(t&&!t.closed)return e();n()})}return e()})}function Ye(){var t=null;return new Z(function(n){"complete"==ou.document.readyState?n():(t=function(){n()},nn(window,"load",t))}).s(function(n){throw en(window,"load",t),n})}function $e(){return Ze(void 0)?Ye().then(function(){return new Z(function(t,n){var e=ou.document,i=setTimeout(function(){n(Error("Cordova framework is not ready."))},1e3);e.addEventListener("deviceready",function(){clearTimeout(i),t()},!1)})}):et(Error("Cordova must run in an Android or iOS file scheme."))}function Ze(t){return t=t||ri(),!("file:"!==ci()||!t.toLowerCase().match(/iphone|ipad|ipod|android/))}function Qe(){var t=ou.window;try{return!(!t||t==t.top)}catch(t){return!1}}function ti(){return iu.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":iu.INTERNAL.hasOwnProperty("node")?"Node":"Browser"}function ni(){var t=ti();return"ReactNative"===t||"Node"===t}function ei(t){var n=t.toLowerCase();return b(n,"opera/")||b(n,"opr/")||b(n,"opios/")?"Opera":b(n,"iemobile")?"IEMobile":b(n,"msie")||b(n,"trident/")?"IE":b(n,"edge/")?"Edge":b(n,"firefox/")?$c:b(n,"silk/")?"Silk":b(n,"blackberry")?"Blackberry":b(n,"webos")?"Webos":!b(n,"safari/")||b(n,"chrome/")||b(n,"crios/")||b(n,"android")?!b(n,"chrome/")&&!b(n,"crios/")||b(n,"edge/")?b(n,"android")?"Android":(t=t.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==t.length?t[1]:"Other":Zc:"Safari"}function ii(t,n){n=n||[];var e,i=[],r={};for(e in Qc)r[Qc[e]]=!0;for(e=0;en)throw Error("Short delay should be less than long delay!");this.c=t,this.b=n,t=e||ri(),i=i||ti(),this.a=We(t)||"ReactNative"===i}function wi(){var t=ou.document;return!t||void 0===t.visibilityState||"visible"==t.visibilityState}function yi(){var t=ou.document,n=null;return wi()||!t?nt():new Z(function(e){n=function(){wi()&&(t.removeEventListener("visibilitychange",n,!1),e())},t.addEventListener("visibilitychange",n,!1)}).s(function(e){throw t.removeEventListener("visibilitychange",n,!1),e})}function Ii(t){try{var n=new Date(parseInt(t,10));if(!isNaN(n.getTime())&&!/[^0-9]/.test(t))return n.toUTCString()}catch(t){}return null}function Ti(t,n,e){th?Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e}):t[n]=e}function ki(t,n){if(n)for(var e in n)n.hasOwnProperty(e)&&Ti(t,e,n[e])}function Ai(t){var n={};return ki(n,t),n}function Ei(t){var n,e={};for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function Ni(t,n){if(!n||!n.length)return!0;if(!t)return!1;for(var e=0;e Auth section -> Sign in method tab.",t):"http"==i||"https"==i?e=m("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",t):n="operation-not-supported-in-this-environment",Pi.call(this,n,e)}function pr(t,n,e){Pi.call(this,t,e),t=n||{},t.rb&&Ti(this,"email",t.rb),t.Y&&Ti(this,"phoneNumber",t.Y),t.credential&&Ti(this,"credential",t.credential)}function dr(t){if(t.code){var n=t.code||"";0==n.indexOf(hh)&&(n=n.substring(hh.length));var e={credential:ur(t)};if(t.email)e.rb=t.email;else{if(!t.phoneNumber)return new Pi(n,t.message||void 0);e.Y=t.phoneNumber}return new pr(n,e,t.message)}return null}function vr(t){this.f=t}function mr(t,n,e){var i="Node"==ti();if(!(i=ou.XMLHttpRequest||i&&iu.INTERNAL.node&&iu.INTERNAL.node.XMLHttpRequest))throw new Pi("internal-error","The XMLHttpRequest compatibility library was not found.");this.b=t,t=n||{},this.i=t.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token",this.l=t.secureTokenTimeout||Sh,this.c=x(t.secureTokenHeaders||Oh),this.g=t.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",this.h=t.firebaseTimeout||Ph,this.a=x(t.firebaseHeaders||Ch),e&&(this.a["X-Client-Version"]=e,this.c["X-Client-Version"]=e),this.f=new Me,this.o=new vr(i)}function gr(t,n){n?t.a["X-Firebase-Locale"]=n:delete t.a["X-Firebase-Locale"]}function br(t,n){n?(t.a["X-Client-Version"]=n,t.c["X-Client-Version"]=n):(delete t.a["X-Client-Version"],delete t.c["X-Client-Version"])}function wr(t,n,e,i,r,o,a){gi()?(He()?t=l(t.m,t):(Eh||(Eh=new Z(function(t,n){yr(t,n)})),t=l(t.u,t)),t(n,e,i,r,o,a)):e&&e(null)}function yr(t,n){((window.gapi||{}).client||{}).request?t():(ou[Rh]=function(){((window.gapi||{}).client||{}).request?t():n(Error("CORS_UNSUPPORTED"))},Ln(De(At(_h,{onload:Rh})),function(){n(Error("CORS_UNSUPPORTED"))}))}function Ir(t,n){return new Z(function(e,i){"refresh_token"==n.grant_type&&n.refresh_token||"authorization_code"==n.grant_type&&n.code?wr(t,t.i+"?key="+encodeURIComponent(t.b),function(t){t?t.error?i(Mr(t)):t.access_token&&t.refresh_token?e(t):i(new Pi("internal-error")):i(new Pi("network-request-failed"))},"POST",""+ce(n),t.c,t.l.get()):i(new Pi("internal-error"))})}function Tr(t,n,e,i,r,o){var a=ee(t.g+n);te(a,"key",t.b),o&&te(a,"cb",""+uu());var s="GET"==e;if(s)for(var u in i)i.hasOwnProperty(u)&&te(a,u,i[u]);return new Z(function(n,o){wr(t,""+a,function(t){t?t.error?o(Mr(t,r||{})):n(t):o(new Pi("network-request-failed"))},e,s?void 0:Mt(li(i)),t.a,t.h.get())})}function kr(t){if(!Gc.test(t.email))throw new Pi("invalid-email")}function Ar(t){"email"in t&&kr(t)}function Er(t,n){return Ur(t,Mh,{identifier:n,continueUri:ui()?qe():"http://localhost"}).then(function(t){return t.allProviders||[]})}function Nr(t){return Ur(t,Bh,{}).then(function(t){return t.authorizedDomains||[]})}function Sr(t){if(!t[Nh])throw new Pi("internal-error")}function Or(t){if(t.phoneNumber||t.temporaryProof){if(!t.phoneNumber||!t.temporaryProof)throw new Pi("internal-error")}else{if(!t.sessionInfo)throw new Pi("missing-verification-id");if(!t.code)throw new Pi("missing-verification-code")}}function Pr(t,n){return Ur(t,Gh,n)}function Cr(t,n,e){return Ur(t,Fh,{idToken:n,deleteProvider:e})}function _r(t){if(!t.requestUri||!t.sessionId&&!t.postBody)throw new Pi("internal-error")}function Rr(t){var n=null;if(t.needConfirmation?(t.code="account-exists-with-different-credential",n=dr(t)):"FEDERATED_USER_ID_ALREADY_LINKED"==t.errorMessage?(t.code="credential-already-in-use",n=dr(t)):"EMAIL_EXISTS"==t.errorMessage&&(t.code="email-already-in-use",n=dr(t)),n)throw n;if(!t[Nh])throw new Pi("internal-error")}function Dr(t,n){return n.returnIdpCredential=!0,Ur(t,$h,n)}function Lr(t,n){return n.returnIdpCredential=!0,Ur(t,Qh,n)}function xr(t,n){return n.returnIdpCredential=!0,n.autoCreate=!1,Ur(t,Zh,n)}function jr(t){if(!t.oobCode)throw new Pi("invalid-action-code")}function Ur(t,n,e){if(!Ni(e,n.ea))return et(new Pi("internal-error"));var i,r=n.yb||"POST";return nt(e).then(n.D).then(function(){return n.T&&(e.returnSecureToken=!0),Tr(t,n.endpoint,r,e,n.Lb,n.nb||!1)}).then(function(t){return i=t}).then(n.O).then(function(){if(!n.ga)return i;if(!(n.ga in i))throw new Pi("internal-error");return i[n.ga]})}function Mr(t,n){var e=(t.error&&t.error.errors&&t.error.errors[0]||{}).reason||"",i={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(e=i[e]?new Pi(i[e]):null)return e;e=t.error&&t.error.message||"",i={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",INVALID_MESSAGE_PAYLOAD:"invalid-message-payload",INVALID_RECIPIENT_EMAIL:"invalid-recipient-email",INVALID_SENDER:"invalid-sender",EMAIL_NOT_FOUND:"user-not-found",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",DYNAMIC_LINK_NOT_ACTIVATED:"dynamic-link-not-activated",INVALID_APP_ID:"invalid-app-id",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password",OPERATION_NOT_ALLOWED:"operation-not-allowed",USER_CANCELLED:"user-cancelled",CAPTCHA_CHECK_FAILED:"captcha-check-failed",INVALID_APP_CREDENTIAL:"invalid-app-credential",INVALID_CODE:"invalid-verification-code",INVALID_PHONE_NUMBER:"invalid-phone-number",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_APP_CREDENTIAL:"missing-app-credential",MISSING_CODE:"missing-verification-code",MISSING_PHONE_NUMBER:"missing-phone-number",MISSING_SESSION_INFO:"missing-verification-id",QUOTA_EXCEEDED:"quota-exceeded",SESSION_EXPIRED:"code-expired",INVALID_CONTINUE_URI:"invalid-continue-uri",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",MISSING_IOS_BUNDLE_ID:"missing-ios-bundle-id",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash"},j(i,n||{}),n=(n=e.match(/^[^\s]+\s*:\s*(.*)$/))&&1n.c?Bn(n,Rc,56-n.c):Bn(n,Rc,n.b-(n.c-56));for(var i=63;56<=i;i--)n.f[i]=255&e,e/=256;for(Xn(n),i=e=0;i>r&255;return Sn(t)}function xo(t,n,e,i){var r=Do(),o=new hr(n,i,null,r,new Pi("no-auth-event")),a=oi("BuildInfo.packageName",ou);if("string"!=typeof a)throw new Pi("invalid-cordova-configuration");var s=oi("BuildInfo.displayName",ou),u={};if(ri().toLowerCase().match(/iphone|ipad|ipod/))u.ibi=a;else{if(!ri().toLowerCase().match(/android/))return et(new Pi("operation-not-supported-in-this-environment"));u.apn=a}s&&(u.appDisplayName=s),r=Lo(r),u.sessionId=r;var c=Zr(t.u,t.i,t.l,n,e,null,i,t.m,u,t.o);return t.ba().then(function(){var n=t.h;return t.A.a.set(bf,o.B(),n)}).then(function(){var n=oi("cordova.plugins.browsertab.isAvailable",ou);if("function"!=typeof n)throw new Pi("invalid-cordova-configuration");var e=null;n(function(n){if(n){if("function"!=typeof(e=oi("cordova.plugins.browsertab.openUrl",ou)))throw new Pi("invalid-cordova-configuration");e(c)}else{if("function"!=typeof(e=oi("cordova.InAppBrowser.open",ou)))throw new Pi("invalid-cordova-configuration");n=ri(),n=!(!n.match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!n.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),t.a=e(c,n?"_blank":"_system","location=yes")}})})}function jo(t,n){for(var e=0;et.f&&(t.a=t.f),n)}function ha(t,n){fa(t),t.b=gn(ca(t,n)).then(function(){return t.l?nt():yi()}).then(function(){return t.h()}).then(function(){ha(t,!0)}).s(function(n){t.i(n)&&ha(t,!1)})}function fa(t){t.b&&(t.b.cancel(),t.b=null)}function la(t){this.f=t,this.b=this.a=null,this.c=0}function pa(t,n){var e=n[Nh],i=n.refreshToken;n=da(n.expiresIn),t.b=e,t.c=n,t.a=i}function da(t){return uu()+1e3*parseInt(t,10)}function va(t,n){return Ir(t.f,n).then(function(n){return t.b=n.access_token,t.c=da(n.expires_in),t.a=n.refresh_token,{accessToken:t.b,expirationTime:t.c,refreshToken:t.a}}).s(function(n){throw"auth/user-token-expired"==n.code&&(t.a=null),n})}function ma(t,n){this.a=t||null,this.b=n||null,ki(this,{lastSignInTime:Ii(n||null),creationTime:Ii(t||null)})}function ga(t){return new ma(t.a,t.b)}function ba(t,n,e,i,r,o){ki(this,{uid:t,displayName:i||null,photoURL:r||null,email:e||null,phoneNumber:o||null,providerId:n})}function wa(t,n){Bt.call(this,t);for(var e in n)this[e]=n[e]}function ya(t,n,e){this.A=[],this.G=t.apiKey,this.o=t.appName,this.w=t.authDomain||null,t=iu.SDK_VERSION?ii(iu.SDK_VERSION):null,this.c=new mr(this.G,Vr(Lh),t),this.h=new la(this.c),Oa(this,n[Nh]),pa(this.h,n),Ti(this,"refreshToken",this.h.a),Ra(this,e||{}),fn.call(this),this.I=!1,this.w&&si()&&(this.a=Yo(this.w,this.G,this.o)),this.N=[],this.i=null,this.l=Ea(this),this.U=l(this.Ga,this);var i=this;this.ha=null,this.ra=function(t){i.na(t.h)},this.W=null,this.R=[],this.qa=function(t){Ta(i,t.f)},this.V=null}function Ia(t,n){t.W&&en(t.W,"languageCodeChanged",t.ra),(t.W=n)&&Zt(n,"languageCodeChanged",t.ra)}function Ta(t,n){t.R=n,br(t.c,iu.SDK_VERSION?ii(iu.SDK_VERSION,t.R):null)}function ka(t,n){t.V&&en(t.V,"frameworkChanged",t.qa),(t.V=n)&&Zt(n,"frameworkChanged",t.qa)}function Aa(t){try{return iu.app(t.o).auth()}catch(n){throw new Pi("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+t.o+"'!")}}function Ea(t){return new ua(function(){return t.F(!0)},function(t){return!(!t||"auth/network-request-failed"!=t.code)},function(){var n=t.h.c-uu()-3e5;return 0r||r>=Ef.length)throw new Pi("internal-error","Argument validator received an unsupported number of arguments.");e=Ef[r],i=(i?"":e+" argument ")+(n.name?'"'+n.name+'" ':"")+"must be "+n.K+".";break t}i=null}}if(i)throw new Pi("argument-error",t+" failed: "+i)}function _s(n,e){return{name:n||"",K:"a valid string",optional:!!e,M:t}}function Rs(){return{name:"opt_forceRefresh",K:"a boolean",optional:!0,M:n}}function Ds(t,n){return{name:t||"",K:"a valid object",optional:!!n,M:c}}function Ls(t,n){return{name:t||"",K:"a function",optional:!!n,M:u}}function xs(t,n){return{name:t||"",K:"null",optional:!!n,M:o}}function js(){return{name:"",K:"an HTML element",optional:!1,M:function(t){return!!(t&&t instanceof Element)}}}function Us(){return{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(t){return!!(t&&t instanceof ls)}}}function Ms(){return{name:"app",K:"an instance of Firebase App",optional:!0,M:function(t){return!!(t&&t instanceof iu.app.App)}}}function Vs(t){return{name:t?t+"Credential":"credential",K:t?"a valid "+t+" credential":"a valid credential",optional:!1,M:function(n){if(!n)return!1;var e=!t||n.providerId===t;return!(!n.wa||!e)}}}function Fs(){return{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}}function Ks(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(n){return!!(n&&t(n.type)&&u(n.verify))}}}function qs(t,n,e,i){return{name:e||"",K:t.K+" or "+n.K,optional:!!i,M:function(e){return t.M(e)||n.M(e)}}}function Xs(t,n,e,i,r,o){if(Ti(this,"type","recaptcha"),this.b=this.c=null,this.m=!1,this.l=n,this.a=e||{theme:"light",type:"image"},this.g=[],this.a[Of])throw new Pi("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");if(this.h="invisible"===this.a[Pf],!Dt(n)||!this.h&&Dt(n).hasChildNodes())throw new Pi("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.u=new mr(t,o||null,r||null),this.o=i||function(){return null};var a=this;this.i=[];var s=this.a[Nf];this.a[Nf]=function(t){if(Bs(a,t),"function"==typeof s)s(t);else if("string"==typeof s){var n=oi(s,ou);"function"==typeof n&&n(t)}};var u=this.a[Sf];this.a[Sf]=function(){if(Bs(a,null),"function"==typeof u)u();else if("string"==typeof u){var t=oi(u,ou);"function"==typeof t&&t()}}}function Bs(t,n){for(var e=0;e>>0),su=0,uu=Date.now||function(){return+new Date};d(v,Error),v.prototype.name="CustomError";var cu=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},hu=/&/g,fu=//g,pu=/"/g,du=/'/g,vu=/\x00/g,mu=/[\x00&<>"']/;d(y,v),y.prototype.name="AssertionError";var gu,bu=Array.prototype.indexOf?function(t,n,e){return Array.prototype.indexOf.call(t,n,e)}:function(n,e,i){if(i=null==i?0:0>i?Math.max(0,n.length+i):i,t(n))return t(e)&&1==e.length?n.indexOf(e,i):-1;for(;iparseFloat(Ru)){Eu=Lu+"";break t}}Eu=Ru}var xu,ju={},Uu=ou.document;xu=Uu&&Su?V()||("CSS1Compat"==Uu.compatMode?parseInt(Eu,10):5):void 0,X.prototype.get=function(){if(0"),Rt(""),Rt("
");var ec={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"},ic={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},rc=/\uffff/.test("￿")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g,oc=0,ac={};qt.prototype.oa=!1,qt.prototype.ta=function(){if(this.Fa)for(;this.Fa.length;)this.Fa.shift()()};var sc=Object.freeze||function(t){return t},uc=!Su||9<=+xu,cc=Su&&!F("9"),hc=function(){if(!ou.addEventListener||!Object.defineProperty)return!1;var t=!1,n=Object.defineProperty({},"passive",{get:function(){t=!0}});return ou.addEventListener("test",i,n),ou.removeEventListener("test",i,n),t}();Bt.prototype.c=function(){this.Ab=!1},d(Ht,Bt);var fc=sc({2:"touch",3:"pen",4:"mouse"});Ht.prototype.c=function(){Ht.ib.c.call(this);var t=this.a;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,cc)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}},Ht.prototype.g=function(){return this.a};var lc="closure_listenable_"+(1e6*Math.random()|0),pc=0,dc="closure_lm_"+(1e6*Math.random()|0),vc={},mc=0,gc="__closure_events_fn_"+(1e9*Math.random()>>>0);d(fn,qt),fn.prototype[lc]=!0,fn.prototype.removeEventListener=function(t,n,e,i){en(this,t,n,e,i)},fn.prototype.ta=function(){if(fn.ib.ta.call(this),this.u){var t,n=this.u,e=0;for(t in n.a){for(var i=n.a[t],r=0;r=In(this).value)for(u(n)&&(n=n()),t=new bn(t,n+"",this.f),e&&(t.a=e),e="log:"+t.b,(t=ou.console)&&t.timeStamp&&t.timeStamp(e),(t=ou.msWriteProfilerMark)&&t(e),e=this;e;)e=e.a};var Tc={},kc=null;eu=kn.prototype,eu.P=function(){An(this);for(var t=[],n=0;n=--n.l&&n.cancel()}this.v?this.v.call(this.o,this):this.u=!0,this.a||(t=new Vn,Dn(this),Rn(this,!1,t))}},_n.prototype.m=function(t,n){this.i=!1,Rn(this,t,n)},_n.prototype.A=function(t){Dn(this),Rn(this,!0,t)},_n.prototype.then=function(t,n,e){var i,r,o=new Z(function(t,n){i=t,r=n});return xn(this,i,function(t){t instanceof Vn?o.cancel():r(t)}),o.then(t,n,e)},K(_n),d(Mn,v),Mn.prototype.message="Deferred has already fired",Mn.prototype.name="AlreadyCalledError",d(Vn,v),Vn.prototype.message="Deferred was canceled",Vn.prototype.name="CanceledError",Fn.prototype.c=function(){throw delete Sc[this.a],this.b};var Nc,Sc={};d(qn,Kn);for(var Oc=64,Pc=Oc-1,Cc=[],_c=0;_cthis.c-3e4?this.a?va(this,{grant_type:"refresh_token",refresh_token:this.a}):nt(null):nt({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},ma.prototype.B=function(){return{lastLoginAt:this.b,createdAt:this.a}},d(wa,Bt),d(ya,fn),ya.prototype.na=function(t){this.ha=t,gr(this.c,t)},ya.prototype.$=function(){return this.ha},ya.prototype.Ka=function(){return O(this.R)},ya.prototype.Ga=function(){this.l.b&&(fa(this.l),this.l.start())},Ti(ya.prototype,"providerId","firebase"),eu=ya.prototype,eu.reload=function(){var t=this;return Ya(this,La(this).then(function(){return Fa(t).then(function(){return Ca(t)}).then(Da)}))},eu.F=function(t){var n=this;return Ya(this,La(this).then(function(){return n.h.getToken(t)}).then(function(t){if(!t)throw new Pi("internal-error");return t.accessToken!=n.pa&&(Oa(n,t.accessToken),ln(n,new wa("tokenChanged"))),Ma(n,"refreshToken",t.refreshToken),t.accessToken}))},eu.getToken=function(t){return nh["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]||(nh["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead.")),this.F(t)},eu.gc=function(t){if(!(t=t.users)||!t.length)throw new Pi("internal-error");t=t[0],Ra(this,{uid:t.localId,displayName:t.displayName,photoURL:t.photoUrl,email:t.email,emailVerified:!!t.emailVerified,phoneNumber:t.phoneNumber,lastLoginAt:t.lastLoginAt,createdAt:t.createdAt});for(var n=Xa(t),e=0;ethis.o&&(this.o=0),0==this.o&&Es(this)&&Sa(Es(this)),this.removeAuthTokenListener(t)},eu.addAuthTokenListener=function(t){var n=this;this.m.push(t),Ps(this,this.i.then(function(){n.l||A(n.m,t)&&t(Ns(n))}))},eu.removeAuthTokenListener=function(t){N(this.m,function(n){return n==t})},eu.delete=function(){this.l=!0;for(var t=0;tt.b&&(t.b++,e.next=t.a,t.a=e)}function T(){this.b=this.a=null}function E(){var t=Du,e=null;return t.a&&(e=t.a,t.a=t.a.next,t.a||(t.b=null),e.next=null),e}function k(){this.next=this.b=this.a=null}function A(e,n){var i=e.length,r=t(e)?e.split(""):e;for(--i;0<=i;--i)i in r&&n.call(void 0,r[i],i,e)}function N(e){t:{for(var n=Hi,i=e.length,r=t(e)?e.split(""):e,o=0;on?null:t(e)?e.charAt(n):e[n]}function S(t,e){return 0<=vu(t,e)}function _(t,e){e=vu(t,e);var n;return(n=0<=e)&&Array.prototype.splice.call(t,e,1),n}function O(t,e){var n=0;A(t,function(i,r){e.call(void 0,i,r,t)&&1==Array.prototype.splice.call(t,r,1).length&&n++})}function P(t){return Array.prototype.concat.apply([],arguments)}function C(t){var e=t.length;if(0")&&(t=t.replace(Tu,">")),-1!=t.indexOf('"')&&(t=t.replace(Eu,""")),-1!=t.indexOf("'")&&(t=t.replace(ku,"'")),-1!=t.indexOf("\0")&&(t=t.replace(Au,"�")),t):t}function L(t,e){return-1!=t.indexOf(e)}function x(t,e){return te?1:0}function M(t){return L(pu,t)}function j(t,e){for(var n in t)e.call(void 0,t[n],n,t)}function U(t){for(var e in t)return!1;return!0}function V(t){var e,n={};for(e in t)n[e]=t[e];return n}function F(t,e){for(var n,i,r=1;ri.keyCode||void 0!=i.returnValue)){t:{var r=!1;if(0==i.keyCode)try{i.keyCode=-1;break t}catch(t){r=!0}(r||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],r=e.b;r;r=r.parentNode)i.push(r);for(t=t.type,r=i.length-1;0<=r;r--){e.b=i[r];var o=Rt(i[r],t,!0,e);n=n&&o}for(r=0;re)throw Error("Bad port number "+e);t.i=e}else t.i=null}function Qt(t,e,n){e instanceof se?(t.a=e,pe(t.a,t.f)):(n||(e=oe(e,vc)),t.a=new se(e,t.f))}function te(t,e,n){t.a.set(e,n)}function ee(t,e){return t.a.get(e)}function ne(t){return t instanceof Yt?new Yt(t):new Yt(t,void 0)}function ie(t,e){var n=new Yt(null,void 0);return $t(n,"https"),t&&(n.b=t),e&&(n.g=e),n}function re(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function oe(e,n,i){return t(e)?(e=encodeURI(e).replace(n,ae),i&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function ae(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function se(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function ue(t){t.a||(t.a=new Xt,t.b=0,t.c&&Jt(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function ce(t){var e=Gt(t);if(void 0===e)throw Error("Keys are undefined");var n=new se(null,void 0);t=qt(t);for(var i=0;i2*t.c&&Wt(t)))}function fe(t,e){return ue(t),e=de(t,e),zt(t.a.b,e)}function le(t,e,n){he(t,e),0"),s=s.join("")}return s=o.createElement(s),u&&(t(u)?s.className=u:a(u)?s.className=u.join(" "):Pe(s,u)),2t||qu&&$u&&!(9<$u))}function qe(t){return t=(t||nn()).toLowerCase(),!!(t.match(/android/)||t.match(/webos/)||t.match(/iphone|ipad|ipod/)||t.match(/blackberry/)||t.match(/windows phone/)||t.match(/iemobile/))}function Ge(t){t=t||cu.window;try{t.close()}catch(t){}}function Be(t,e,n){var i=""+Math.floor(1e9*Math.random());e=e||500,n=n||600;var r=(window.screen.availHeight-n)/2,o=(window.screen.availWidth-e)/2;e={width:e,height:n,top:0',t=_e(t),a.document.write(Se(t)),a.document.close())):(a=i.open(Ee(e),n,a))&&t.noopener&&(a.opener=null),a)try{a.focus()}catch(t){}return a}function Xe(t){return new X(function(e){function n(){Ht(2e3).then(function(){if(t&&!t.closed)return n();e()})}return n()})}function We(){var t=null;return new X(function(e){"complete"==cu.document.readyState?e():(t=function(){e()},_t(window,"load",t))}).o(function(e){throw Ot(window,"load",t),e})}function ze(){return Je(void 0)?We().then(function(){return new X(function(t,e){var n=cu.document,i=setTimeout(function(){e(Error("Cordova framework is not ready."))},1e3);n.addEventListener("deviceready",function(){clearTimeout(i),t()},!1)})}):Y(Error("Cordova must run in an Android or iOS file scheme."))}function Je(t){return t=t||nn(),!("file:"!==un()||!t.toLowerCase().match(/iphone|ipad|ipod|android/))}function Ye(){var t=cu.window;try{return!(!t||t==t.top)}catch(t){return!1}}function $e(){return"object"!=typeof cu.window&&"function"==typeof cu.importScripts}function Ze(){return su.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":su.INTERNAL.hasOwnProperty("node")?"Node":$e()?"Worker":"Browser"}function Qe(){var t=Ze();return"ReactNative"===t||"Node"===t}function tn(t){var e=t.toLowerCase();return L(e,"opera/")||L(e,"opr/")||L(e,"opios/")?"Opera":L(e,"iemobile")?"IEMobile":L(e,"msie")||L(e,"trident/")?"IE":L(e,"edge/")?"Edge":L(e,"firefox/")?Oc:L(e,"silk/")?"Silk":L(e,"blackberry")?"Blackberry":L(e,"webos")?"Webos":!L(e,"safari/")||L(e,"chrome/")||L(e,"crios/")||L(e,"android")?!L(e,"chrome/")&&!L(e,"crios/")||L(e,"edge/")?L(e,"android")?"Android":(t=t.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==t.length?t[1]:"Other":Pc:"Safari"}function en(t,e){e=e||[];var n,i=[],r={};for(n in Cc)r[Cc[n]]=!0;for(n=0;ne)throw Error("Short delay should be less than long delay!");this.c=t,this.b=e,t=nn(),e=Ze(),this.a=qe(t)||"ReactNative"===e}function gn(){var t=cu.document;return!t||void 0===t.visibilityState||"visible"==t.visibilityState}function wn(){var t=cu.document,e=null;return gn()||!t?J():new X(function(n){e=function(){gn()&&(t.removeEventListener("visibilitychange",e,!1),n())},t.addEventListener("visibilitychange",e,!1)}).o(function(n){throw t.removeEventListener("visibilitychange",e,!1),n})}function yn(t){try{var e=new Date(parseInt(t,10));if(!isNaN(e.getTime())&&!/[^0-9]/.test(t))return e.toUTCString()}catch(t){}return null}function In(){return!(!rn("fireauth.oauthhelper",cu)&&!rn("fireauth.iframe",cu))}function Tn(t,e,n){Rc?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n}):t[e]=n}function En(t,e){if(e)for(var n in e)e.hasOwnProperty(n)&&Tn(t,n,e[n])}function kn(t){var e={};return En(e,t),e}function An(t){var e,n={};for(e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}function Nn(t,e){if(!e||!e.length)return!0;if(!t)return!1;for(var n=0;n>4),64!=a&&(e(o<<4&240|a>>2),64!=s&&e(a<<6&192|s))}}function Mn(){if(!Qc){Qc={},th={};for(var t=0;65>t;t++)Qc[t]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(t),th[Qc[t]]=t,62<=t&&(th["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(t)]=t)}}function jn(t){this.c=t.sub,lu(),this.a=t.provider_id||t.firebase&&t.firebase.sign_in_provider||null,this.b=!!t.is_anonymous||"anonymous"==this.a}function Un(t){if(t=t.split("."),3!=t.length)return null;t=t[1];for(var e=(4-t.length%4)%4,n=0;n Auth section -> Sign in method tab.",t):"http"==i||"https"==i?n=R("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",t):e="operation-not-supported-in-this-environment",On.call(this,e,n)}function Ii(t,e,n){On.call(this,t,n),t=e||{},t.ub&&Tn(this,"email",t.ub),t.Y&&Tn(this,"phoneNumber",t.Y),t.credential&&Tn(this,"credential",t.credential)}function Ti(t){if(t.code){var e=t.code||"";0==e.indexOf(qc)&&(e=e.substring(qc.length));var n={credential:vi(t)};if(t.email)n.ub=t.email;else{if(!t.phoneNumber)return new On(e,t.message||void 0);n.Y=t.phoneNumber}return new Ii(e,n,t.message)}return null}function Ei(){}function ki(t){return t.c||(t.c=t.b())}function Ai(){}function Ni(t){if(!t.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],n=0;n<4;n++){var i=e[n];try{return new ActiveXObject(i),t.f=i}catch(t){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return t.f}function Si(){}function _i(){this.a=new XDomainRequest,this.readyState=0,this.onreadystatechange=null,this.responseText="",this.status=-1,this.statusText="",this.a.onload=l(this.ac,this),this.a.onerror=l(this.zb,this),this.a.onprogress=l(this.bc,this),this.a.ontimeout=l(this.ec,this)}function Oi(t,e){t.readyState=e,t.onreadystatechange&&t.onreadystatechange()}function Pi(t,e,n){this.reset(t,e,n,void 0,void 0)}function Ci(t){this.f=t,this.b=this.c=this.a=null}function Ri(t,e){this.name=t,this.value=e}function Di(t){return t.c?t.c:t.a?Di(t.a):(w("Root logger has no level set."),null)}function Li(t){vh||(vh=new Ci(""),ph[""]=vh,vh.c=lh);var e;if(!(e=ph[t])){e=new Ci(t);var n=t.lastIndexOf("."),i=t.substr(n+1);n=Li(t.substr(0,n)),n.b||(n.b={}),n.b[i]=e,e.a=n,ph[t]=e}return e}function xi(t,e){t&&t.log(dh,e,void 0)}function Mi(t){this.f=t}function ji(t){jt.call(this),this.i=t,this.readyState=mh,this.status=0,this.responseText=this.statusText="",this.onreadystatechange=null,this.g=new Headers,this.b=null,this.h="GET",this.c="",this.a=!1,this.f=Li("goog.net.FetchXmlHttp")}function Ui(t){t.onreadystatechange&&t.onreadystatechange.call(t)}function Vi(t){jt.call(this),this.headers=new Xt,this.D=t||null,this.c=!1,this.A=this.a=null,this.h=this.N=this.l="",this.f=this.I=this.i=this.G=!1,this.g=0,this.s=null,this.m=bh,this.v=this.O=!1}function Fi(t,e,n,i,r){if(t.a)throw Error("[goog.net.XhrIo] Object is active with another request="+t.l+"; newUri="+e);n=n?n.toUpperCase():"GET",t.l=e,t.h="",t.N=n,t.G=!1,t.c=!0,t.a=t.D?t.D.a():uh.a(),t.A=ki(t.D?t.D:uh),t.a.onreadystatechange=l(t.Db,t);try{xi(t.b,$i(t,"Opening Xhr")),t.I=!0,t.a.open(n,e+"",!0),t.I=!1}catch(e){return xi(t.b,$i(t,"Error opening Xhr: "+e.message)),void qi(t,e)}e=i||"";var o=new Xt(t.headers);r&&Bt(r,function(t,e){o.set(e,t)}),r=N(o.T()),i=cu.FormData&&e instanceof cu.FormData,!S(wh,n)||r||i||o.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),o.forEach(function(t,e){this.a.setRequestHeader(e,t)},t),t.m&&(t.a.responseType=t.m),"withCredentials"in t.a&&t.a.withCredentials!==t.O&&(t.a.withCredentials=t.O);try{Wi(t),0e;e++){r=0|n[e-15],i=0|n[e-2];var o=(0|n[e-16])+((r>>>7|r<<25)^(r>>>18|r<<14)^r>>>3)|0,a=(0|n[e-7])+((i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10)|0;n[e]=o+a|0}i=0|t.a[0],r=0|t.a[1];var s=0|t.a[2],u=0|t.a[3],c=0|t.a[4],h=0|t.a[5],f=0|t.a[6];for(o=0|t.a[7],e=0;64>e;e++){var l=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&r^i&s^r&s)|0;a=c&h^~c&f,o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0,a=a+(0|yf[e])|0,a=o+(a+(0|n[e])|0)|0,o=f,f=h,h=c,c=u+a|0,u=s,s=r,r=i,i=a+l|0}t.a[0]=t.a[0]+i|0,t.a[1]=t.a[1]+r|0,t.a[2]=t.a[2]+s|0,t.a[3]=t.a[3]+u|0,t.a[4]=t.a[4]+c|0,t.a[5]=t.a[5]+h|0,t.a[6]=t.a[6]+f|0,t.a[7]=t.a[7]+o|0}function Lo(e,n,i){void 0===i&&(i=n.length);var r=0,o=e.c;if(t(n))for(;r=a&&a==(0|a)))throw Error("message must be a byte array");e.f[o++]=a,o==e.b&&(Do(e),o=0)}}e.c=o,e.g+=i}function xo(){Ro.call(this,8,_f)}function Mo(t,e,n,i,r){this.u=t,this.i=e,this.l=n,this.m=i||null,this.s=r||null,this.h=e+":"+n,this.v=new Po,this.g=new _o(this.h),this.f=null,this.b=[],this.a=this.c=null}function jo(t){return new On("invalid-cordova-configuration",t)}function Uo(){for(var t=20,e=[];0e.c?Lo(e,Nf,56-e.c):Lo(e,Nf,e.b-(e.c-56));for(var i=63;56<=i;i--)e.f[i]=255&n,n/=256;for(Do(e),i=n=0;i>r&255;return Dn(t)}function Fo(t,e,n,i){var r=Uo(),o=new bi(e,i,null,r,new On("no-auth-event")),a=rn("BuildInfo.packageName",cu);if("string"!=typeof a)throw new On("invalid-cordova-configuration");var s=rn("BuildInfo.displayName",cu),u={};if(nn().toLowerCase().match(/iphone|ipad|ipod/))u.ibi=a;else{if(!nn().toLowerCase().match(/android/))return Y(new On("operation-not-supported-in-this-environment"));u.apn=a}s&&(u.appDisplayName=s),r=Vo(r),u.sessionId=r;var c=Zr(t.u,t.i,t.l,e,n,null,i,t.m,u,t.s);return t.ca().then(function(){var e=t.h;return t.v.a.set(If,o.C(),e)}).then(function(){var e=rn("cordova.plugins.browsertab.isAvailable",cu);if("function"!=typeof e)throw new On("invalid-cordova-configuration");var n=null;e(function(e){if(e){if("function"!=typeof(n=rn("cordova.plugins.browsertab.openUrl",cu)))throw new On("invalid-cordova-configuration");n(c)}else{if("function"!=typeof(n=rn("cordova.InAppBrowser.open",cu)))throw new On("invalid-cordova-configuration");e=nn(),e=!(!e.match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!e.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),t.a=n(c,e?"_blank":"_system","location=yes")}})})}function Ko(t,e){for(var n=0;nt.f&&(t.a=t.f),e)}function va(t,e){t.stop(),t.b=Ht(pa(t,e)).then(function(){return wn()}).then(function(){return t.h()}).then(function(){va(t,!0)}).o(function(e){t.i(e)&&va(t,!1)})}function ma(t){this.f=t,this.b=this.a=null,this.c=0}function ba(t,e){var n=e[kh],i=e.refreshToken;e=ga(e.expiresIn),t.b=n,t.c=e,t.a=i}function ga(t){return lu()+1e3*parseInt(t,10)}function wa(t,e){return wr(t.f,e).then(function(e){return t.b=e.access_token,t.c=ga(e.expires_in),t.a=e.refresh_token,{accessToken:t.b,expirationTime:t.c,refreshToken:t.a}}).o(function(e){throw"auth/user-token-expired"==e.code&&(t.a=null),e})}function ya(t,e){this.a=t||null,this.b=e||null,En(this,{lastSignInTime:yn(e||null),creationTime:yn(t||null)})}function Ia(t){return new ya(t.a,t.b)}function Ta(t,e,n,i,r,o){En(this,{uid:t,displayName:i||null,photoURL:r||null,email:n||null,phoneNumber:o||null,providerId:e})}function Ea(t,e){gt.call(this,t);for(var n in e)this[n]=e[n]}function ka(t,e,n){this.D=[],this.G=t.apiKey,this.s=t.appName,this.A=t.authDomain||null,t=su.SDK_VERSION?en(su.SDK_VERSION):null,this.b=new pr(this.G,Vr(Rh),t),this.h=new ma(this.b),Ra(this,e[kh]),ba(this.h,e),Tn(this,"refreshToken",this.h.a),Ma(this,n||{}),jt.call(this),this.I=!1,this.A&&an()&&(this.a=ea(this.A,this.G,this.s)),this.N=[],this.i=null,this.l=Oa(this),this.U=l(this.Ga,this);var i=this;this.ha=null,this.sa=function(t){i.na(t.h)},this.W=null,this.O=[],this.ra=function(t){Na(i,t.f)},this.V=null}function Aa(t,e){t.W&&Ot(t.W,"languageCodeChanged",t.sa),(t.W=e)&&At(e,"languageCodeChanged",t.sa)}function Na(t,e){t.O=e,mr(t.b,su.SDK_VERSION?en(su.SDK_VERSION,t.O):null)}function Sa(t,e){t.V&&Ot(t.V,"frameworkChanged",t.ra),(t.V=e)&&At(e,"frameworkChanged",t.ra)}function _a(t){try{return su.app(t.s).auth()}catch(e){throw new On("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+t.s+"'!")}}function Oa(t){return new da(function(){return t.F(!0)},function(t){return!(!t||"auth/network-request-failed"!=t.code)},function(){var e=t.h.c-lu()-3e5;return 0r||r>=Kf.length)throw new On("internal-error","Argument validator received an unsupported number of arguments.");n=Kf[r],i=(i?"":n+" argument ")+(e.name?'"'+e.name+'" ':"")+"must be "+e.K+".";break t}i=null}}if(i)throw new On("argument-error",t+" failed: "+i)}function Gs(e,n){return{name:e||"",K:"a valid string",optional:!!n,M:t}}function Bs(){return{name:"opt_forceRefresh",K:"a boolean",optional:!0,M:e}}function Xs(t,e){return{name:t||"",K:"a valid object",optional:!!e,M:c}}function Ws(t,e){return{name:t||"",K:"a function",optional:!!e,M:u}}function zs(t,e){return{name:t||"",K:"null",optional:!!e,M:o}}function Js(){return{name:"",K:"an HTML element",optional:!1,M:function(t){return!!(t&&t instanceof Element)}}}function Ys(){return{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(t){return!!(t&&t instanceof ms)}}}function $s(){return{name:"app",K:"an instance of Firebase App",optional:!0,M:function(t){return!!(t&&t instanceof su.app.App)}}}function Zs(t){return{name:t?t+"Credential":"credential",K:t?"a valid "+t+" credential":"a valid credential",optional:!1,M:function(e){if(!e)return!1;var n=!t||e.providerId===t;return!(!e.xa||!n)}}}function Qs(){return{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}}function tu(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(e){return!!(e&&t(e.type)&&u(e.verify))}}}function eu(t,e,n,i){return{name:n||"",K:t.K+" or "+e.K,optional:!!i,M:function(n){return t.M(n)||e.M(n)}}}function nu(t,e){for(var n in e){var i=e[n].name;t[i]=ru(i,t[n],e[n].j)}}function iu(t,e,n,i){t[e]=ru(e,n,i)}function ru(t,e,n){function i(){var t=Array.prototype.slice.call(arguments);return qs(o,n,t),e.apply(this,t)}if(!n)return e;var r,o=ou(t);for(r in e)i[r]=e[r];for(r in e.prototype)i.prototype[r]=e.prototype[r];return i}function ou(t){return t=t.split("."),t[t.length-1]}var au,su=n(7).default,uu=uu||{},cu=this,hu="closure_uid_"+(1e9*Math.random()>>>0),fu=0,lu=Date.now||function(){return+new Date};p(b,Error),b.prototype.name="CustomError",p(g,b),g.prototype.name="AssertionError",y.prototype.get=function(){if(0/g,Eu=/"/g,ku=/'/g,Au=/\x00/g,Nu=/[\x00&<>"']/;t:{var Su=cu.navigator;if(Su){var _u=Su.userAgent;if(_u){pu=_u;break t}}pu=""}var Ou,Pu,Cu="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),Ru=!1,Du=new T,Lu=0,xu=2,Mu=3;W.prototype.reset=function(){this.f=this.b=this.g=this.a=null,this.c=!1};var ju=new y(function(){return new W},function(t){t.reset()});X.prototype.then=function(t,e,n){return nt(this,u(t)?t:null,u(e)?e:null,n)},v(X),au=X.prototype,au.ga=function(t,e){return t=z(t,t,e),t.c=!0,et(this,t),this},au.o=function(t,e){return nt(this,null,t,e)},au.cancel=function(t){this.a==Lu&&q(function(){tt(this,new ft(t))},this)},au.Jc=function(t){this.a=Lu,it(this,xu,t)},au.Kc=function(t){this.a=Lu,it(this,Mu,t)},au.Ub=function(){for(var t;t=st(this);)ut(this,t,this.a,this.i);this.h=!1};var Uu=K;p(ft,b),ft.prototype.name="cancel";var Vu=0,Fu={};lt.prototype.pa=!1,lt.prototype.ua=function(){if(this.oa)for(;this.oa.length;)this.oa.shift()()},pt[" "]=i;var Ku,Hu=M("Opera"),qu=M("Trident")||M("MSIE"),Gu=M("Edge"),Bu=Gu||qu,Xu=M("Gecko")&&!(L(pu.toLowerCase(),"webkit")&&!M("Edge"))&&!(M("Trident")||M("MSIE"))&&!M("Edge"),Wu=L(pu.toLowerCase(),"webkit")&&!M("Edge");t:{var zu="",Ju=function(){var t=pu;return Xu?/rv:([^\);]+)(\)|;)/.exec(t):Gu?/Edge\/([\d\.]+)/.exec(t):qu?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(t):Wu?/WebKit\/(\S+)/.exec(t):Hu?/(?:Version)[ \/]?(\S+)/.exec(t):void 0}();if(Ju&&(zu=Ju?Ju[1]:""),qu){var Yu=mt();if(null!=Yu&&Yu>parseFloat(zu)){Ku=Yu+"";break t}}Ku=zu}var $u,Zu={},Qu=cu.document;$u=Qu&&qu?mt()||("CSS1Compat"==Qu.compatMode?parseInt(Ku,10):5):void 0;var tc=Object.freeze||function(t){return t},ec=!qu||9<=+$u,nc=qu&&!bt("9"),ic=function(){if(!cu.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return cu.addEventListener("test",i,e),cu.removeEventListener("test",i,e),t}();gt.prototype.c=function(){this.Eb=!1},p(wt,gt);var rc=tc({2:"touch",3:"pen",4:"mouse"});wt.prototype.c=function(){wt.lb.c.call(this);var t=this.a;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,nc)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}},wt.prototype.g=function(){return this.a};var oc="closure_listenable_"+(1e6*Math.random()|0),ac=0;Tt.prototype.add=function(t,e,n,i,r){var o=""+t;(t=this.a[o])||(t=this.a[o]=[],this.b++);var a=kt(t,e,i,r);return-1>>0);p(jt,lt),jt.prototype[oc]=!0,jt.prototype.addEventListener=function(t,e,n,i){At(this,t,e,n,i)},jt.prototype.removeEventListener=function(t,e,n,i){Ot(this,t,e,n,i)},jt.prototype.dispatchEvent=function(e){var n,i=this.Ta;if(i)for(n=[];i;i=i.Ta)n.push(i);i=this.Mb;var r=e.type||e;if(t(e))e=new gt(e,i);else if(e instanceof gt)e.target=e.target||i;else{var o=e;e=new gt(r,i),F(e,o)}if(o=!0,n)for(var a=n.length-1;0<=a;a--){var s=e.b=n[a];o=Ft(s,r,!0,e)&&o}if(s=e.b=i,o=Ft(s,r,!0,e)&&o,o=Ft(s,r,!1,e)&&o,n)for(a=0;a"),_e(""),_e("
");var Ac={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"},Nc={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},Sc=/\uffff/.test("￿")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g,_c=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Oc="Firefox",Pc="Chrome",Cc={Pc:"FirebaseCore-web",Rc:"FirebaseUI-web"};bn.prototype.get=function(){return this.a?this.b:this.c};var Rc,Dc={};try{var Lc={};Object.defineProperty(Lc,"abcd",{configurable:!0,enumerable:!0,value:1}),Object.defineProperty(Lc,"abcd",{configurable:!0,enumerable:!0,value:2}),Rc=2==Lc.abcd}catch(t){Rc=!1}var xc="EMAIL_SIGNIN",Mc="email",jc="newEmail",Uc="requestType",Vc="email",Fc="fromEmail",Kc="data",Hc="operation";p(On,Error),On.prototype.C=function(){return{code:this.code,message:this.message}},On.prototype.toJSON=function(){return this.C()};var qc="auth/",Gc={"argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-already-in-use":"The email address is already in use by another account.","expired-action-code":"The action code has expired. ","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal error has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal error has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-email":"The email address is badly formatted.","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal error has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network error (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal error has occurred.","no-such-provider":"User was not linked to an account with the given provider.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","user-cancelled":"User did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled."},Bc="android",Xc="handleCodeInApp",Wc="iOS",zc="url",Jc="installApp",Yc="minimumVersion",$c="packageName",Zc="bundleId",Qc=null,th=null;jn.prototype.f=function(){return this.b};var eh="oauth_consumer_key oauth_nonce oauth_signature oauth_signature_method oauth_timestamp oauth_token oauth_version".split(" "),nh=["client_id","response_type","scope","redirect_uri","state"],ih={Qc:{Ma:"locale",Aa:500,za:600,Na:"facebook.com",cb:nh},Sc:{Ma:null,Aa:500,za:620,Na:"github.com",cb:nh},Tc:{Ma:"hl",Aa:515,za:680,Na:"google.com",cb:nh},Zc:{Ma:"lang",Aa:485,za:705,Na:"twitter.com",cb:eh}},rh="idToken",oh="providerId";p(Hn,Kn),p(qn,Hn),p(Gn,Hn),p(Bn,Hn),p(Xn,Hn),Jn.prototype.xa=function(t){return Rr(t,Yn(this))},Jn.prototype.c=function(t,e){var n=Yn(this);return n.idToken=e,Dr(t,n)},Jn.prototype.f=function(t,e){return zn(Lr(t,Yn(this)),e)},Jn.prototype.C=function(){var t={providerId:this.providerId,signInMethod:this.signInMethod};return this.idToken&&(t.oauthIdToken=this.idToken),this.accessToken&&(t.oauthAccessToken=this.accessToken),this.secret&&(t.oauthTokenSecret=this.secret),t},$n.prototype.Ca=function(t){return this.tb=V(t),this},p(Zn,$n),Zn.prototype.ta=function(t){return S(this.a,t)||this.a.push(t),this},Zn.prototype.yb=function(){return C(this.a)},Zn.prototype.credential=function(t,e){if(!t&&!e)throw new On("argument-error","credential failed: must provide the ID token and/or the access token.");return new Jn(this.providerId,{idToken:t||null,accessToken:e||null},this.providerId)},p(Qn,Zn),Tn(Qn,"PROVIDER_ID","facebook.com"),Tn(Qn,"FACEBOOK_SIGN_IN_METHOD","facebook.com"),p(ei,Zn),Tn(ei,"PROVIDER_ID","github.com"),Tn(ei,"GITHUB_SIGN_IN_METHOD","github.com"),p(ii,Zn),Tn(ii,"PROVIDER_ID","google.com"),Tn(ii,"GOOGLE_SIGN_IN_METHOD","google.com"),p(oi,$n),Tn(oi,"PROVIDER_ID","twitter.com"),Tn(oi,"TWITTER_SIGN_IN_METHOD","twitter.com"),si.prototype.xa=function(t){return this.signInMethod==ui.EMAIL_LINK_SIGN_IN_METHOD?Mr(t,Vh,{email:this.a,oobCode:this.b}):Mr(t,nf,{email:this.a,password:this.b})},si.prototype.c=function(t,e){return this.signInMethod==ui.EMAIL_LINK_SIGN_IN_METHOD?Mr(t,Fh,{idToken:e,email:this.a,oobCode:this.b}):Mr(t,Yh,{idToken:e,email:this.a,password:this.b})},si.prototype.f=function(t,e){return zn(this.xa(t),e)},si.prototype.C=function(){return{email:this.a,password:this.b,signInMethod:this.signInMethod}},En(ui,{PROVIDER_ID:"password"}),En(ui,{EMAIL_LINK_SIGN_IN_METHOD:"emailLink"}),En(ui,{EMAIL_PASSWORD_SIGN_IN_METHOD:"password"}),fi.prototype.xa=function(t){return t.Sa(li(this))},fi.prototype.c=function(t,e){var n=li(this);return n.idToken=e,Mr(t,of,n)},fi.prototype.f=function(t,e){var n=li(this);return n.operation="REAUTH",t=Mr(t,af,n),zn(t,e)},fi.prototype.C=function(){var t={providerId:"phone"};return this.a.Ra&&(t.verificationId=this.a.Ra),this.a.Qa&&(t.verificationCode=this.a.Qa),this.a.Ea&&(t.temporaryProof=this.a.Ea),this.a.Y&&(t.phoneNumber=this.a.Y),t},di.prototype.Sa=function(e,n){var i=this.a.b;return J(n.verify()).then(function(r){if(!t(r))throw new On("argument-error","An implementation of firebase.auth.ApplicationVerifier.prototype.verify() must return a firebase.Promise that resolves with a string.");switch(n.type){case"recaptcha":return _r(i,{phoneNumber:e,recaptchaToken:r}).then(function(t){return"function"==typeof n.reset&&n.reset(),t},function(t){throw"function"==typeof n.reset&&n.reset(),t});default:throw new On("argument-error",'Only firebase.auth.ApplicationVerifiers with type="recaptcha" are currently supported.')}})},En(di,{PROVIDER_ID:"phone"}),En(di,{PHONE_SIGN_IN_METHOD:"phone"}),bi.prototype.C=function(){return{type:this.b,eventId:this.c,urlResponse:this.f,sessionId:this.g,error:this.a&&this.a.C()}};var ah=null;wi.prototype.subscribe=function(t){var e=this;this.a.push(t),this.b||(this.b=function(t){for(var n=0;n=Di(this).value)for(u(e)&&(e=e()),t=new Pi(t,e+"",this.f),n&&(t.a=n),n=this;n;)n=n.a};var ph={},vh=null;p(Mi,Ei),Mi.prototype.a=function(){return new ji(this.f)},Mi.prototype.b=function(t){return function(){return t}}({}),p(ji,jt);var mh=0;au=ji.prototype,au.open=function(t,e){if(this.readyState!=mh)throw this.abort(),Error("Error reopening a connection");this.h=t,this.c=e,this.readyState=1,Ui(this)},au.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var e={headers:this.g,method:this.h,credentials:void 0,cache:void 0};t&&(e.body=t),this.i.fetch(new Request(this.c,e)).then(this.dc.bind(this),this.Ab.bind(this))},au.abort=function(){this.responseText="",this.g=new Headers,this.status=0,1<=this.readyState&&this.a&&4!=this.readyState&&(this.readyState=4,this.a=!1,Ui(this)),this.readyState=mh},au.dc=function(t){this.a&&(this.b||(this.b=t.headers,this.readyState=2,Ui(this)),this.a&&(this.readyState=3,Ui(this),this.a&&t.text().then(this.cc.bind(this,t),this.Ab.bind(this))))},au.cc=function(t,e){this.a&&(this.status=t.status,this.statusText=t.statusText,this.responseText=e,this.readyState=4,Ui(this))},au.Ab=function(t){var e=this.f;e&&e.log(fh,"Failed to fetch url "+this.c,t instanceof Error?t:Error(t)),this.a&&(this.readyState=4,Ui(this))},au.setRequestHeader=function(t,e){this.g.append(t,e)},au.getResponseHeader=function(t){return this.b?this.b.get(t.toLowerCase())||"":((t=this.f)&&t.log(fh,"Attempting to get response header but no headers have been received for url: "+this.c,void 0),"")},au.getAllResponseHeaders=function(){if(!this.b){var t=this.f;return t&&t.log(fh,"Attempting to get all response headers but no headers have been received for url: "+this.c,void 0),""}t=[];for(var e=this.b.entries(),n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},p(Vi,jt);var bh="";Vi.prototype.b=Li("goog.net.XhrIo");var gh=/^https?$/i,wh=["POST","PUT"];au=Vi.prototype,au.Fa=function(){void 0!==uu&&this.a&&(this.h="Timed out after "+this.g+"ms, aborting",xi(this.b,$i(this,this.h)),this.dispatchEvent("timeout"),this.abort(8))},au.abort=function(){this.a&&this.c&&(xi(this.b,$i(this,"Aborting")),this.c=!1,this.f=!0,this.a.abort(),this.f=!1,this.dispatchEvent("complete"),this.dispatchEvent("abort"),Xi(this))},au.ua=function(){this.a&&(this.c&&(this.c=!1,this.f=!0,this.a.abort(),this.f=!1),Xi(this,!0)),Vi.lb.ua.call(this)},au.Db=function(){this.pa||(this.I||this.i||this.f?Bi(this):this.sc())},au.sc=function(){Bi(this)},au.getResponse=function(){try{if(!this.a)return null;if("response"in this.a)return this.a.response;switch(this.m){case bh:case"text":return this.a.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in this.a)return this.a.mozResponseArrayBuffer}var t=this.b;return t&&t.log(hh,"Response type "+this.m+" is not supported on this browser",void 0),null}catch(t){return xi(this.b,"Can not get response: "+t.message),null}},Zi.prototype.cancel=function(t){if(this.a)this.c instanceof Zi&&this.c.cancel();else{if(this.b){var e=this.b;delete this.b,t?e.cancel(t):0>=--e.l&&e.cancel()}this.v?this.v.call(this.s,this):this.u=!0,this.a||(t=new ar(this),tr(this),Qi(this,!1,t))}},Zi.prototype.m=function(t,e){this.i=!1,Qi(this,t,e)},Zi.prototype.D=function(){tr(this),Qi(this,!0,null)},Zi.prototype.then=function(t,e,n){var i,r,o=new X(function(t,e){i=t,r=e});return nr(this,i,function(t){t instanceof ar?o.cancel():r(t)}),o.then(t,e,n)},v(Zi),p(or,b),or.prototype.message="Deferred has already fired",or.prototype.name="AlreadyCalledError",p(ar,b),ar.prototype.message="Deferred was canceled",ar.prototype.name="CanceledError",sr.prototype.c=function(){throw delete yh[this.a],this.b};var yh={},Ih=0,Th=1;p(lr,b),p(dr,Ei),dr.prototype.a=function(){return new this.f},dr.prototype.b=function(){return{}};var Eh,kh="idToken",Ah=new bn(3e4,6e4),Nh={"Content-Type":"application/x-www-form-urlencoded"},Sh=new bn(3e4,6e4),_h={"Content-Type":"application/json"};pr.prototype.m=function(t,e,n,i,r,o){var a=new Vi(this.c);if(o){a.g=Math.max(0,o);var s=setTimeout(function(){a.dispatchEvent("timeout")},o)}Ut(a,"complete",function(){s&&clearTimeout(s);var t=null;try{t=JSON.parse(Yi(this))||null}catch(e){t=null}e&&e(t)}),Vt(a,"ready",function(){s&&clearTimeout(s),dt(this)}),Vt(a,"timeout",function(){s&&clearTimeout(s),dt(this),e&&e(null)}),Fi(a,t,n,i,r)};var Oh=be("https://apis.google.com/js/client.js?onload=%{onload}"),Ph="__fcb"+Math.floor(1e6*Math.random());pr.prototype.u=function(t,e,n,i,r){var o=this;Eh.then(function(){window.gapi.client.setApiKey(o.b);var a=window.gapi.auth.getToken();window.gapi.auth.setToken(null),window.gapi.client.request({path:t,method:n,body:i,headers:r,authType:"none",callback:function(t){window.gapi.auth.setToken(a),e&&e(t)}})}).o(function(t){e&&e({error:{message:t&&t.message||"CORS_UNSUPPORTED"}})})},pr.prototype.jb=function(){return Mr(this,$h,{})},pr.prototype.mb=function(t,e){return Mr(this,Jh,{idToken:t,email:e})},pr.prototype.nb=function(t,e){return Mr(this,Yh,{idToken:t,password:e})};var Ch={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"};au=pr.prototype,au.ob=function(t,e){var n={idToken:t},i=[];return j(Ch,function(t,r){var o=e[r];null===o?i.push(t):r in e&&(n[r]=o)}),i.length&&(n.deleteAttribute=i),Mr(this,Jh,n)},au.gb=function(t,e){return t={requestType:"PASSWORD_RESET",email:t},F(t,e),Mr(this,Gh,t)},au.hb=function(t,e){return t={requestType:"EMAIL_SIGNIN",email:t},F(t,e),Mr(this,Hh,t)},au.fb=function(t,e){return t={requestType:"VERIFY_EMAIL",idToken:t},F(t,e),Mr(this,qh,t)},au.Sa=function(t){return Mr(this,rf,t)},au.Wa=function(t,e){return Mr(this,Wh,{oobCode:t,newPassword:e})},au.Ia=function(t){return Mr(this,Lh,{oobCode:t})},au.Ua=function(t){return Mr(this,Dh,{oobCode:t})};var Rh,Dh={endpoint:"setAccountInfo",w:xr,$:"email"},Lh={endpoint:"resetPassword",w:xr,J:function(t){if(!t.email||!t.requestType)throw new On("internal-error")}},xh={endpoint:"signupNewUser",w:function(t){if(Ir(t),!t.password)throw new On("weak-password")},J:Nr,P:!0},Mh={endpoint:"createAuthUri"},jh={endpoint:"deleteAccount",S:["idToken"]},Uh={endpoint:"setAccountInfo",S:["idToken","deleteProvider"],w:function(t){if(!a(t.deleteProvider))throw new On("internal-error")}},Vh={endpoint:"emailLinkSignin",S:["email","oobCode"],w:Ir,J:Nr,P:!0},Fh={endpoint:"emailLinkSignin",S:["idToken","email","oobCode"],w:Ir,J:Nr,P:!0},Kh={endpoint:"getAccountInfo"},Hh={endpoint:"getOobConfirmationCode",S:["requestType"],w:function(t){if("EMAIL_SIGNIN"!=t.requestType)throw new On("internal-error");Ir(t)},$:"email"},qh={endpoint:"getOobConfirmationCode",S:["idToken","requestType"],w:function(t){if("VERIFY_EMAIL"!=t.requestType)throw new On("internal-error")},$:"email"},Gh={endpoint:"getOobConfirmationCode",S:["requestType"],w:function(t){if("PASSWORD_RESET"!=t.requestType)throw new On("internal-error");Ir(t)},$:"email"},Bh={pb:!0,endpoint:"getProjectConfig",Cb:"GET"},Xh={pb:!0,endpoint:"getRecaptchaParam",Cb:"GET",J:function(t){if(!t.recaptchaSiteKey)throw new On("internal-error")}},Wh={endpoint:"resetPassword",w:xr,$:"email"},zh={endpoint:"sendVerificationCode",S:["phoneNumber","recaptchaToken"],$:"sessionInfo"},Jh={endpoint:"setAccountInfo",S:["idToken"],w:Tr,P:!0},Yh={endpoint:"setAccountInfo",S:["idToken"],w:function(t){if(Tr(t),!t.password)throw new On("weak-password")},J:Nr,P:!0},$h={endpoint:"signupNewUser",J:Nr,P:!0},Zh={endpoint:"verifyAssertion",w:Pr,J:Cr,P:!0},Qh={endpoint:"verifyAssertion",w:Pr,J:function(t){if(t.errorMessage&&"USER_NOT_FOUND"==t.errorMessage)throw new On("user-not-found");if(t.errorMessage)throw jr(t.errorMessage);if(!t[kh])throw new On("internal-error")},P:!0},tf={endpoint:"verifyAssertion",w:function(t){if(Pr(t),!t.idToken)throw new On("internal-error")},J:Cr,P:!0},ef={endpoint:"verifyCustomToken",w:function(t){if(!t.token)throw new On("invalid-custom-token")},J:Nr,P:!0},nf={endpoint:"verifyPassword",w:function(t){if(Ir(t),!t.password)throw new On("wrong-password")},J:Nr,P:!0},rf={endpoint:"verifyPhoneNumber",w:Sr,J:Nr},of={endpoint:"verifyPhoneNumber",w:function(t){if(!t.idToken)throw new On("internal-error");Sr(t)},J:function(t){if(t.temporaryProof)throw t.code="credential-already-in-use",Ti(t);Nr(t)}},af={Tb:{USER_NOT_FOUND:"user-not-found"},endpoint:"verifyPhoneNumber",w:Sr,J:Nr},sf={Vc:{Ya:"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",eb:"https://securetoken.googleapis.com/v1/token",id:"p"},Xc:{Ya:"https://staging-www.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/",eb:"https://staging-securetoken.sandbox.googleapis.com/v1/token",id:"s"},Yc:{Ya:"https://www-googleapis-test.sandbox.google.com/identitytoolkit/v3/relyingparty/",eb:"https://test-securetoken.sandbox.googleapis.com/v1/token",id:"t"}};Rh=Vr("__EID__")?"__EID__":void 0;var uf=be("https://apis.google.com/js/api.js?onload=%{onload}"),cf=new bn(3e4,6e4),hf=new bn(5e3,15e3),ff=null;Br.prototype.toString=function(){return this.f?te(this.a,"v",this.f):he(this.a.a,"v"),this.b?te(this.a,"eid",this.b):he(this.a.a,"eid"),this.c.length?te(this.a,"fw",this.c.join(",")):he(this.a.a,"fw"),""+this.a},Xr.prototype.toString=function(){var t=ie(this.m,"/__/auth/handler");if(te(t,"apiKey",this.u),te(t,"appName",this.c),te(t,"authType",this.l),this.a.isOAuthProvider){var e=this.a;try{var n=su.app(this.c).auth().aa()}catch(t){n=null}e.Xa=n,te(t,"providerId",this.a.providerId),e=this.a,n=fn(e.tb);for(var i in n)n[i]=""+n[i];i=e.zc,n=V(n);for(var r=0;rthis.c-3e4?this.a?wa(this,{grant_type:"refresh_token",refresh_token:this.a}):J(null):J({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},ya.prototype.C=function(){return{lastLoginAt:this.b,createdAt:this.a}},p(Ea,gt),p(ka,jt),ka.prototype.na=function(t){this.ha=t,vr(this.b,t)},ka.prototype.aa=function(){return this.ha},ka.prototype.Ka=function(){return C(this.O)},ka.prototype.Ga=function(){this.l.b&&(this.l.stop(),this.l.start())},Tn(ka.prototype,"providerId","firebase"),au=ka.prototype,au.reload=function(){var t=this;return ts(this,Ua(this).then(function(){return Ga(t).then(function(){return La(t)}).then(ja)}))},au.F=function(t){var e=this;return ts(this,Ua(this).then(function(){return e.h.getToken(t)}).then(function(t){if(!t)throw new On("internal-error");return t.accessToken!=e.qa&&(Ra(e,t.accessToken),e.dispatchEvent(new Ea("tokenChanged"))),Ha(e,"refreshToken",t.refreshToken),t.accessToken}))},au.getToken=function(t){return Dc["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]||(Dc["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead.")),this.F(t)},au.tc=function(t){if(!(t=t.users)||!t.length)throw new On("internal-error");t=t[0],Ma(this,{uid:t.localId,displayName:t.displayName,photoURL:t.photoUrl,email:t.email,emailVerified:!!t.emailVerified,phoneNumber:t.phoneNumber,lastLoginAt:t.lastLoginAt,createdAt:t.createdAt});for(var e=Wa(t),n=0;nthis.s&&(this.s=0),0==this.s&&Os(this)&&Ca(Os(this)),this.removeAuthTokenListener(t)},au.addAuthTokenListener=function(t){var e=this;this.m.push(t),Ds(this,this.i.then(function(){e.l||S(e.m,t)&&t(Ps(e))}))},au.removeAuthTokenListener=function(t){O(this.m,function(e){return e==t})},au.delete=function(){this.l=!0;for(var t=0;tn?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r},t.each=function(e,t){if(Array.isArray(e))for(var n=0;n=Math.pow(2,-1022)?(a=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=a+1023,o=Math.round(e*Math.pow(2,52-a)-Math.pow(2,52))):(i=0,o=Math.round(e/Math.pow(2,-1074)))),u=[],s=52;s;s-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(s=11;s;s-=1)u.push(i%2?1:0),i=Math.floor(i/2);u.push(n?1:0),u.reverse(),l=u.join("");var h="";for(s=0;s<64;s+=8){var c=parseInt(l.substr(s,8),2).toString(16);1===c.length&&(c="0"+c),h+=c}return h.toLowerCase()},t.isChromeExtensionContentScript=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},t.isWindowsStoreApp=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI},t.errorForServerCode=function(e,t){var n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==e?n="Client doesn't have permission to access the desired data.":"unavailable"==e&&(n="The service is unavailable");var r=Error(e+" at "+t.path+": "+n);return r.code=e.toUpperCase(),r},t.e=RegExp("^-?\\d{1,10}$"),t.tryParseInt=function(e){if(t.e.test(e)){var n=+e;if(n>=-2147483648&&n<=2147483647)return n}return null},t.exceptionGuard=function(e){try{e()}catch(e){setTimeout(function(){var n=e.stack||"";throw t.warn("Exception was thrown by user callback.",n),e},Math.floor(0))}},t.callUserCallback=function(e){for(var n=[],r=1;r=0},t.exportPropGetter=function(e,t,n){Object.defineProperty(e,t,{get:n})},t.setTimeoutNonBlocking=function(e,t){var n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=n(0),o=function(){function e(e,t){if(void 0===t){this.n=e.split("/");for(var n=0,r=0;r0&&(this.n[n]=this.n[r],n++);this.n.length=n,this.i=0}else this.n=e,this.i=t}return Object.defineProperty(e,"Empty",{get:function(){return new e("")},enumerable:!0,configurable:!0}),e.prototype.getFront=function(){return this.i>=this.n.length?null:this.n[this.i]},e.prototype.getLength=function(){return this.n.length-this.i},e.prototype.popFront=function(){var t=this.i;return t=this.n.length)return null;for(var t=[],n=this.i;n0&&n.push(i[r]);return new e(n,0)},e.prototype.isEmpty=function(){return this.i>=this.n.length},e.relativePath=function(t,n){var r=t.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return e.relativePath(t.popFront(),n.popFront());throw Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+t+")")},e.comparePaths=function(e,t){for(var n=e.slice(),i=t.slice(),o=0;oe.getLength())return!1;for(;t0&&(this.l+=1),this.u.push(e),this.l+=i.stringLength(e),this.f()},e.prototype.pop=function(){var e=this.u.pop();this.l-=i.stringLength(e),this.u.length>0&&(this.l-=1)},e.prototype.f=function(){if(this.l>e.MAX_PATH_LENGTH_BYTES)throw Error(this.o+"has a key path longer than "+e.MAX_PATH_LENGTH_BYTES+" bytes ("+this.l+").");if(this.u.length>e.MAX_PATH_DEPTH)throw Error(this.o+"path specified exceeds the maximum depth that can be written ("+e.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},e.prototype.toErrorString=function(){return 0==this.u.length?"":"in property '"+this.u.join(".")+"'"},e}();t.ValidationPath=a},function(e,t,n){"use strict";function r(e){a=e}function i(e){s=e}var o=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var a,s,u=n(14),l=n(1),h=n(5),c=n(15);t.setNodeFromJSON=r,t.setMaxNode=i;var p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.compare=function(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?l.nameCompare(e.name,t.name):i},t.prototype.isDefinedOn=function(e){return!e.getPriority().isEmpty()},t.prototype.indexedValueChanged=function(e,t){return!e.getPriority().equals(t.getPriority())},t.prototype.minPost=function(){return h.NamedNode.MIN},t.prototype.maxPost=function(){return new h.NamedNode(l.MAX_NAME,new c.LeafNode("[PRIORITY-POST]",s))},t.prototype.makePost=function(e,t){var n=a(e);return new h.NamedNode(t,new c.LeafNode("[PRIORITY-POST]",n))},t.prototype.toString=function(){return".priority"},t}(u.Index);t.PriorityIndex=p,t.PRIORITY_INDEX=new p},function(e,t,n){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var i,o=n(0),a=n(1),s=n(16),u=n(5),l=n(37),h=n(3),c=n(10),p=n(39),d=n(15),f=n(41),_=function(){function e(e,t,n){this._=e,this.y=t,this.g=n,this.m=null,this.y&&l.validatePriorityNode(this.y),this._.isEmpty()&&o.assert(!this.y||this.y.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(e,"EMPTY_NODE",{get:function(){return i||(i=new e(new s.SortedMap(f.NAME_COMPARATOR),null,p.IndexMap.Default))},enumerable:!0,configurable:!0}),e.prototype.isLeafNode=function(){return!1},e.prototype.getPriority=function(){return this.y||i},e.prototype.updatePriority=function(t){return this._.isEmpty()?this:new e(this._,t,this.g)},e.prototype.getImmediateChild=function(e){if(".priority"===e)return this.getPriority();var t=this._.get(e);return null===t?i:t},e.prototype.getChild=function(e){var t=e.getFront();return null===t?this:this.getImmediateChild(t).getChild(e.popFront())},e.prototype.hasChild=function(e){return null!==this._.get(e)},e.prototype.updateImmediateChild=function(t,n){if(o.assert(n,"We should always be passing snapshot nodes"),".priority"===t)return this.updatePriority(n);var r=new u.NamedNode(t,n),a=void 0,s=void 0,l=void 0;return n.isEmpty()?(a=this._.remove(t),s=this.g.removeFromIndexes(r,this._)):(a=this._.insert(t,n),s=this.g.addToIndexes(r,this._)),l=a.isEmpty()?i:this.y,new e(a,l,s)},e.prototype.updateChild=function(e,t){var n=e.getFront();if(null===n)return t;o.assert(".priority"!==e.getFront()||1===e.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(e.popFront(),t);return this.updateImmediateChild(n,r)},e.prototype.isEmpty=function(){return this._.isEmpty()},e.prototype.numChildren=function(){return this._.count()},e.prototype.val=function(t){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(h.PRIORITY_INDEX,function(a,s){n[a]=s.val(t),r++,o&&e.e.test(a)?i=Math.max(i,+a):o=!1}),!t&&o&&i<2*r){var a=[];for(var s in n)a[s]=n[s];return a}return t&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},e.prototype.hash=function(){if(null===this.m){var e="";this.getPriority().isEmpty()||(e+="priority:"+l.priorityHashText(this.getPriority().val())+":"),this.forEachChild(h.PRIORITY_INDEX,function(t,n){var r=n.hash();""!==r&&(e+=":"+t+":"+r)}),this.m=""===e?"":a.sha1(e)}return this.m},e.prototype.getPredecessorChildName=function(e,t,n){var r=this.C(n);if(r){var i=r.getPredecessorKey(new u.NamedNode(e,t));return i?i.name:null}return this._.getPredecessorKey(e)},e.prototype.getFirstChildName=function(e){var t=this.C(e);if(t){var n=t.minKey();return n&&n.name}return this._.minKey()},e.prototype.getFirstChild=function(e){var t=this.getFirstChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.getLastChildName=function(e){var t=this.C(e);if(t){var n=t.maxKey();return n&&n.name}return this._.maxKey()},e.prototype.getLastChild=function(e){var t=this.getLastChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.forEachChild=function(e,t){var n=this.C(e);return n?n.inorderTraversal(function(e){return t(e.name,e.node)}):this._.inorderTraversal(t)},e.prototype.getIterator=function(e){return this.getIteratorFrom(e.minPost(),e)},e.prototype.getIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getIteratorFrom(e,function(e){return e});for(var r=this._.getIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)<0;)r.getNext(),i=r.peek();return r},e.prototype.getReverseIterator=function(e){return this.getReverseIteratorFrom(e.maxPost(),e)},e.prototype.getReverseIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getReverseIteratorFrom(e,function(e){return e});for(var r=this._.getReverseIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)>0;)r.getNext(),i=r.peek();return r},e.prototype.compareTo=function(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===t.MAX_NODE?-1:0},e.prototype.withIndex=function(t){if(t===c.KEY_INDEX||this.g.hasIndex(t))return this;var n=this.g.addIndex(t,this._);return new e(this._,this.y,n)},e.prototype.isIndexed=function(e){return e===c.KEY_INDEX||this.g.hasIndex(e)},e.prototype.equals=function(e){if(e===this)return!0;if(e.isLeafNode())return!1;var t=e;if(this.getPriority().equals(t.getPriority())){if(this._.count()===t._.count()){for(var n=this.getIterator(h.PRIORITY_INDEX),r=t.getIterator(h.PRIORITY_INDEX),i=n.getNext(),o=r.getNext();i&&o;){if(i.name!==o.name||!i.node.equals(o.node))return!1;i=n.getNext(),o=r.getNext()}return null===i&&null===o}return!1}return!1},e.prototype.C=function(e){return e===c.KEY_INDEX?null:this.g.get(""+e)},e.e=/^(0|[1-9]\d*)$/,e}();t.ChildrenNode=_;var y=function(e){function t(){return e.call(this,new s.SortedMap(f.NAME_COMPARATOR),_.EMPTY_NODE,p.IndexMap.Default)||this}return r(t,e),t.prototype.compareTo=function(e){return e===this?0:1},t.prototype.equals=function(e){return e===this},t.prototype.getPriority=function(){return this},t.prototype.getImmediateChild=function(e){return _.EMPTY_NODE},t.prototype.isEmpty=function(){return!1},t}(_);t.MaxNode=y,t.MAX_NODE=new y,Object.defineProperties(u.NamedNode,{MIN:{value:new u.NamedNode(a.MIN_NAME,_.EMPTY_NODE)},MAX:{value:new u.NamedNode(a.MAX_NAME,t.MAX_NODE)}}),c.KeyIndex.__EMPTY_NODE=_.EMPTY_NODE,d.LeafNode.__childrenNodeConstructor=_,l.setMaxNode(t.MAX_NODE),h.setMaxNode(t.MAX_NODE)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){this.name=e,this.node=t}return e.Wrap=function(t,n){return new e(t,n)},e}();t.NamedNode=r},,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),i=n(0),o=n(1),a=n(0),s=n(0);t.N=/[\[\].#$\/\u0000-\u001F\u007F]/,t.P=/[\[\].#$\u0000-\u001F\u007F]/,t.S=10485760,t.isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!t.N.test(e)},t.isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!t.P.test(e)},t.isValidRootPathString=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),t.isValidPathString(e)},t.isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!o.isInvalidJSONNumber(e)||e&&"object"==typeof e&&i.contains(e,".sv")},t.validateFirebaseDataArg=function(e,n,r,i,o){o&&void 0===r||t.validateFirebaseData(a.errorPrefix(e,n,o),r,i)},t.validateFirebaseData=function(e,n,a){var u=a instanceof r.Path?new r.ValidationPath(a,e):a;if(void 0===n)throw Error(e+"contains undefined "+u.toErrorString());if("function"==typeof n)throw Error(e+"contains a function "+u.toErrorString()+" with contents = "+n);if(o.isInvalidJSONNumber(n))throw Error(e+"contains "+n+" "+u.toErrorString());if("string"==typeof n&&n.length>t.S/3&&s.stringLength(n)>t.S)throw Error(e+"contains a string greater than "+t.S+" utf8 bytes "+u.toErrorString()+" ('"+n.substring(0,50)+"...')");if(n&&"object"==typeof n){var l=!1,h=!1;if(i.forEach(n,function(n,r){if(".value"===n)l=!0;else if(".priority"!==n&&".sv"!==n&&(h=!0,!t.isValidKey(n)))throw Error(e+" contains an invalid key ("+n+") "+u.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');u.push(n),t.validateFirebaseData(e,r,u),u.pop()}),l&&h)throw Error(e+' contains ".value" child '+u.toErrorString()+" in addition to actual children.")}},t.validateFirebaseMergePaths=function(e,n){var i,o;for(i=0;i=0,"Unknown leaf type: "+n),i.assert(a>=0,"Unknown leaf type: "+r),o===a?"object"===r?0:this.T0},e.prototype.peek=function(){if(0===this.O.length)return null;var e=this.O[this.O.length-1];return this.R?this.R(e.key,e.value):{key:e.key,value:e.value}},e}();t.SortedMapIterator=r;var i=function(){function e(t,n,r,i,o){this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:a.EMPTY_NODE,this.right=null!=o?o:a.EMPTY_NODE}return e.prototype.copy=function(t,n,r,i,o){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},e.prototype.count=function(){return this.left.count()+1+this.right.count()},e.prototype.isEmpty=function(){return!1},e.prototype.inorderTraversal=function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)},e.prototype.A=function(){return this.left.isEmpty()?this:this.left.A()},e.prototype.minKey=function(){return this.A().key},e.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},e.prototype.insert=function(e,t,n){var r,i;return i=this,r=n(e,i.key),i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.D()},e.prototype.M=function(){if(this.left.isEmpty())return a.EMPTY_NODE;var e=this;return e.left.L()||e.left.left.L()||(e=e.F()),e=e.copy(null,null,null,e.left.M(),null),e.D()},e.prototype.remove=function(e,t){var n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.L()||n.left.left.L()||(n=n.F()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.L()&&(n=n.x()),n.right.isEmpty()||n.right.L()||n.right.left.L()||(n=n.k()),0===t(e,n.key)){if(n.right.isEmpty())return a.EMPTY_NODE;r=n.right.A(),n=n.copy(r.key,r.value,null,null,n.right.M())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.D()},e.prototype.L=function(){return this.color},e.prototype.D=function(){var e=this;return e.right.L()&&!e.left.L()&&(e=e.W()),e.left.L()&&e.left.left.L()&&(e=e.x()),e.left.L()&&e.right.L()&&(e=e.j()),e},e.prototype.F=function(){var e=this.j();return e.right.left.L()&&(e=e.copy(null,null,null,null,e.right.x()),e=e.W(),e=e.j()),e},e.prototype.k=function(){var e=this.j();return e.left.left.L()&&(e=e.x(),e=e.j()),e},e.prototype.W=function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)},e.prototype.x=function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)},e.prototype.j=function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)},e.prototype.V=function(){var e=this.Q();return Math.pow(2,e)<=this.count()+1},e.prototype.Q=function(){var e;if(this.L()&&this.left.L())throw Error("Red node has red child("+this.key+","+this.value+")");if(this.right.L())throw Error("Right child of ("+this.key+","+this.value+") is red");if((e=this.left.Q())!==this.right.Q())throw Error("Black depths differ");return e+(this.L()?0:1)},e.RED=!0,e.BLACK=!1,e}();t.LLRBNode=i;var o=function(){function e(){}return e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new i(e,t,null)},e.prototype.remove=function(e,t){return this},e.prototype.count=function(){return 0},e.prototype.isEmpty=function(){return!0},e.prototype.inorderTraversal=function(e){return!1},e.prototype.reverseTraversal=function(e){return!1},e.prototype.minKey=function(){return null},e.prototype.maxKey=function(){return null},e.prototype.Q=function(){return 0},e.prototype.L=function(){return!1},e}();t.LLRBEmptyNode=o;var a=function(){function e(t,n){void 0===n&&(n=e.EMPTY_NODE),this.U=t,this.B=n}return e.prototype.insert=function(t,n){return new e(this.U,this.B.insert(t,n,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.remove=function(t){return new e(this.U,this.B.remove(t,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.get=function(e){for(var t,n=this.B;!n.isEmpty();){if(0===(t=this.U(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null},e.prototype.getPredecessorKey=function(e){for(var t,n=this.B,r=null;!n.isEmpty();){if(0===(t=this.U(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw Error("Attempted to find predecessor key for a nonexistent key. What gives?")},e.prototype.isEmpty=function(){return this.B.isEmpty()},e.prototype.count=function(){return this.B.count()},e.prototype.minKey=function(){return this.B.minKey()},e.prototype.maxKey=function(){return this.B.maxKey()},e.prototype.inorderTraversal=function(e){return this.B.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.B.reverseTraversal(e)},e.prototype.getIterator=function(e){return new r(this.B,null,this.U,!1,e)},e.prototype.getIteratorFrom=function(e,t){return new r(this.B,e,this.U,!1,t)},e.prototype.getReverseIteratorFrom=function(e,t){return new r(this.B,e,this.U,!0,t)},e.prototype.getReverseIterator=function(e){return new r(this.B,null,this.U,!0,e)},e.EMPTY_NODE=new o,e}();t.SortedMap=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(43),i=n(11),o=n(2),a=n(44),s=n(86),u=n(97),l=n(0),h=n(1),c=n(0),p=n(98),d=n(25),f=n(100),_=n(49),y=n(101),v=n(50),g=n(106),m=n(32),C=function(){function e(e,t,n){var r=this;this.H=e,this.app=n,this.dataUpdateCount=0,this.G=null,this.K=new y.EventQueue,this.Y=1,this.X=null,this.z=new a.SparseSnapshotTree,this.J=null;var i=new p.AuthTokenProvider(n);if(this.$=d.StatsManager.getCollection(e),t||h.beingCrawled())this.Z=new g.ReadonlyRestClient(this.H,this.ee.bind(this),i),setTimeout(this.te.bind(this,!0),0);else{var o=n.options.databaseAuthVariableOverride;if(void 0!==o&&null!==o){if("object"!=typeof o)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{l.stringify(o)}catch(e){throw Error("Invalid authOverride provided: "+e)}}this.J=new v.PersistentConnection(this.H,this.ee.bind(this),this.te.bind(this),this.ne.bind(this),i,o),this.Z=this.J}i.addTokenChangeListener(function(e){r.Z.refreshAuthToken(e)}),this.re=d.StatsManager.getOrCreateReporter(e,function(){return new f.StatsReporter(r.$,r.Z)}),this.ie(),this.oe=new u.SnapshotHolder,this.ae=new s.SyncTree({startListening:function(e,t,n,i){var o=[],a=r.oe.getNode(e.path);return a.isEmpty()||(o=r.ae.applyServerOverwrite(e.path,a),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.se("connected",!1),this.ue=new s.SyncTree({startListening:function(e,t,n,i){return r.Z.listen(e,n,t,function(t,n){var o=i(t,n);r.K.raiseEventsForChangedPath(e.path,o)}),[]},stopListening:function(e,t){r.Z.unlisten(e,t)}})}return e.prototype.toString=function(){return(this.H.secure?"https://":"http://")+this.H.host},e.prototype.name=function(){return this.H.namespace},e.prototype.serverTime=function(){var e=this.oe.getNode(new o.Path(".info/serverTimeOffset")),t=e.val()||0;return(new Date).getTime()+t},e.prototype.generateServerValues=function(){return r.generateWithValues({timestamp:this.serverTime()})},e.prototype.ee=function(e,t,n,r){this.dataUpdateCount++;var a=new o.Path(e);t=this.X?this.X(e,t):t;var s=[];if(r)if(n){var u=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyTaggedQueryMerge(a,u,r)}else{var l=i.nodeFromJSON(t);s=this.ue.applyTaggedQueryOverwrite(a,l,r)}else if(n){var h=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyServerMerge(a,h)}else{var p=i.nodeFromJSON(t);s=this.ue.applyServerOverwrite(a,p)}var d=a;s.length>0&&(d=this.le(a)),this.K.raiseEventsForChangedPath(d,s)},e.prototype.he=function(e){this.X=e},e.prototype.te=function(e){this.se("connected",e),!1===e&&this.ce()},e.prototype.ne=function(e){var t=this;h.each(e,function(e,n){t.se(n,e)})},e.prototype.se=function(e,t){var n=new o.Path("/.info/"+e),r=i.nodeFromJSON(t);this.oe.updateSnapshot(n,r);var a=this.ae.applyServerOverwrite(n,r);this.K.raiseEventsForChangedPath(n,a)},e.prototype.pe=function(){return this.Y++},e.prototype.setWithPriority=function(e,t,n,o){var a=this;this.de("set",{path:""+e,value:t,priority:n});var s=this.generateServerValues(),u=i.nodeFromJSON(t,n),l=r.resolveDeferredValueSnapshot(u,s),c=this.pe(),p=this.ue.applyUserOverwrite(e,l,c,!0);this.K.queueEvents(p),this.Z.put(""+e,u.val(!0),function(t,n){var r="ok"===t;r||h.warn("set at "+e+" failed: "+t);var i=a.ue.ackUserWrite(c,!r);a.K.raiseEventsForChangedPath(e,i),a.callOnCompleteCallback(o,t,n)});var d=this.fe(e);this.le(d),this.K.raiseEventsForChangedPath(d,[])},e.prototype.update=function(e,t,n){var o=this;this.de("update",{path:""+e,value:t});var a=!0,s=this.generateServerValues(),u={};if(c.forEach(t,function(e,t){a=!1;var n=i.nodeFromJSON(t);u[e]=r.resolveDeferredValueSnapshot(n,s)}),a)h.log("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var l=this.pe(),p=this.ue.applyUserMerge(e,u,l);this.K.queueEvents(p),this.Z.merge(""+e,t,function(t,r){var i="ok"===t;i||h.warn("update at "+e+" failed: "+t);var a=o.ue.ackUserWrite(l,!i),s=a.length>0?o.le(e):e;o.K.raiseEventsForChangedPath(s,a),o.callOnCompleteCallback(n,t,r)}),c.forEach(t,function(t){var n=o.fe(e.child(t));o.le(n)}),this.K.raiseEventsForChangedPath(e,[])}},e.prototype.ce=function(){var e=this;this.de("onDisconnectEvents");var t=this.generateServerValues(),n=r.resolveDeferredValueTree(this.z,t),i=[];n.forEachTree(o.Path.Empty,function(t,n){i=i.concat(e.ue.applyServerOverwrite(t,n));var r=e.fe(t);e.le(r)}),this.z=new a.SparseSnapshotTree,this.K.raiseEventsForChangedPath(o.Path.Empty,i)},e.prototype.onDisconnectCancel=function(e,t){var n=this;this.Z.onDisconnectCancel(""+e,function(r,i){"ok"===r&&n.z.forget(e),n.callOnCompleteCallback(t,r,i)})},e.prototype.onDisconnectSet=function(e,t,n){var r=this,o=i.nodeFromJSON(t);this.Z.onDisconnectPut(""+e,o.val(!0),function(t,i){"ok"===t&&r.z.remember(e,o),r.callOnCompleteCallback(n,t,i)})},e.prototype.onDisconnectSetWithPriority=function(e,t,n,r){var o=this,a=i.nodeFromJSON(t,n);this.Z.onDisconnectPut(""+e,a.val(!0),function(t,n){"ok"===t&&o.z.remember(e,a),o.callOnCompleteCallback(r,t,n)})},e.prototype.onDisconnectUpdate=function(e,t,n){var r=this;if(c.isEmpty(t))return h.log("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.Z.onDisconnectMerge(""+e,t,function(o,a){"ok"===o&&c.forEach(t,function(t,n){var o=i.nodeFromJSON(n);r.z.remember(e.child(t),o)}),r.callOnCompleteCallback(n,o,a)})},e.prototype.addEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.addEventRegistration(e,t):this.ue.addEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.removeEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.removeEventRegistration(e,t):this.ue.removeEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.interrupt=function(){this.J&&this.J.interrupt("repo_interrupt")},e.prototype.resume=function(){this.J&&this.J.resume("repo_interrupt")},e.prototype.stats=function(e){if(void 0===e&&(e=!1),"undefined"!=typeof console){var t;e?(this.G||(this.G=new _.StatsListener(this.$)),t=this.G.get()):t=this.$.get();var n=Object.keys(t).reduce(function(e,t){return Math.max(t.length,e)},0);c.forEach(t,function(e,t){for(var r=e.length;r0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(2),o=n(34),a=n(1);t.parseRepoInfo=function(e){var n=t.parseURL(e),r=n.subdomain;"firebase"===n.domain&&a.fatal(n.host+" is no longer supported. Please use .firebaseio.com instead"),r&&"undefined"!=r||a.fatal("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||a.warnIfPageIsSecure();var s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new o.RepoInfo(n.host,n.secure,r,s),path:new i.Path(n.pathString)}},t.parseURL=function(e){var t="",n="",i="",o="",a=!0,s="https",u=443;if("string"==typeof e){var l=e.indexOf("//");l>=0&&(s=e.substring(0,l-1),e=e.substring(l+2));var h=e.indexOf("/");-1===h&&(h=e.length),t=e.substring(0,h),o=r(e.substring(h));var c=t.split(".");3===c.length?(n=c[1],i=c[0].toLowerCase()):2===c.length&&(n=c[0]),(l=t.indexOf(":"))>=0&&(a="https"===s||"wss"===s,u=parseInt(t.substring(l+1),10))}return{host:t,port:u,domain:n,subdomain:i,secure:a,scheme:s,pathString:o}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(12),a=n(13),s=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this.secure=t,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=e.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=o.PersistentStorage.get("host:"+e)||this.host}return e.prototype.needsQueryParam=function(){return this.host!==this.internalHost},e.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},e.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},e.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},e.prototype.updateHost=function(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&o.PersistentStorage.set("host:"+this.host,this.internalHost))},e.prototype.connectionURL=function(e,t){r.assert("string"==typeof e,"typeof type must == string"),r.assert("object"==typeof t,"typeof params must == object");var n;if(e===a.WEBSOCKET)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(e!==a.LONG_POLLING)throw Error("Unknown connection type: "+e);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(t.ns=this.namespace);var o=[];return i.forEach(t,function(e,t){o.push(e+"="+t)}),n+o.join("&")},e.prototype.toString=function(){var e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e},e.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},e}();t.RepoInfo=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(7),o=n(1),a=n(0),s=function(){function e(e,t){this.Ie=e,this.Oe=t}return e.prototype.cancel=function(e){r.validateArgCount("OnDisconnect.cancel",0,1,arguments.length),r.validateCallback("OnDisconnect.cancel",1,e,!0);var t=new a.Deferred;return this.Ie.onDisconnectCancel(this.Oe,t.wrapCallback(e)),t.promise},e.prototype.remove=function(e){r.validateArgCount("OnDisconnect.remove",0,1,arguments.length),i.validateWritablePath("OnDisconnect.remove",this.Oe),r.validateCallback("OnDisconnect.remove",1,e,!0);var t=new a.Deferred;return this.Ie.onDisconnectSet(this.Oe,null,t.wrapCallback(e)),t.promise},e.prototype.set=function(e,t){r.validateArgCount("OnDisconnect.set",1,2,arguments.length),i.validateWritablePath("OnDisconnect.set",this.Oe),i.validateFirebaseDataArg("OnDisconnect.set",1,e,this.Oe,!1),r.validateCallback("OnDisconnect.set",2,t,!0);var n=new a.Deferred;return this.Ie.onDisconnectSet(this.Oe,e,n.wrapCallback(t)),n.promise},e.prototype.setWithPriority=function(e,t,n){r.validateArgCount("OnDisconnect.setWithPriority",2,3,arguments.length),i.validateWritablePath("OnDisconnect.setWithPriority",this.Oe),i.validateFirebaseDataArg("OnDisconnect.setWithPriority",1,e,this.Oe,!1),i.validatePriority("OnDisconnect.setWithPriority",2,t,!1),r.validateCallback("OnDisconnect.setWithPriority",3,n,!0);var o=new a.Deferred;return this.Ie.onDisconnectSetWithPriority(this.Oe,e,t,o.wrapCallback(n)),o.promise},e.prototype.update=function(e,t){if(r.validateArgCount("OnDisconnect.update",1,2,arguments.length),i.validateWritablePath("OnDisconnect.update",this.Oe),Array.isArray(e)){for(var n={},s=0;s3e4&&(this.nt=v),this._t=null}}else this.de("Window isn't visible. Delaying reconnect."),this.nt=this.rt,this.ft=(new Date).getTime();var t=(new Date).getTime()-this.ft,n=Math.max(0,this.nt-t);n=Math.random()*n,this.de("Trying to reconnect in "+n+"ms"),this.yt(n),this.nt=Math.min(this.rt,1.3*this.nt)}this.te(!1)},t.prototype.Ft=function(){if(this.Wt()){this.de("Making a connection attempt"),this.ft=(new Date).getTime(),this._t=null;var e=this.wt.bind(this),n=this.At.bind(this),r=this.xt.bind(this),i=this.id+":"+t.jt++,o=this,a=this.lastSessionId,l=!1,h=null,c=function(){h?h.close():(l=!0,r())},p=function(e){s.assert(h,"sendRequest call when we're not connected not allowed."),h.sendRequest(e)};this.lt={close:c,sendRequest:p};var _=this.ct;this.ct=!1,this.Ke.getToken(_).then(function(t){l?u.log("getToken() completed but was canceled"):(u.log("getToken() completed. Creating connection."),o.ht=t&&t.accessToken,h=new d.Connection(i,o.H,e,n,r,function(e){u.warn(e+" ("+o.H+")"),o.interrupt("server_kill")},a))}).then(null,function(e){o.de("Failed to get token: "+e),l||(f.CONSTANTS.NODE_ADMIN&&u.warn(e),c())})}},t.prototype.interrupt=function(e){u.log("Interrupting connection for reason: "+e),this.ze[e]=!0,this.lt?this.lt.close():(this.ot&&(clearTimeout(this.ot),this.ot=null),this.tt&&this.xt())},t.prototype.resume=function(e){u.log("Resuming connection for reason: "+e),delete this.ze[e],o.isEmpty(this.ze)&&(this.nt=v,this.lt||this.yt(0))},t.prototype.Dt=function(e){var t=e-(new Date).getTime();this.ne({serverTimeOffset:t})},t.prototype.kt=function(){for(var e=0;e=3&&(this.nt=3e4,this.Ke.notifyForInvalidToken())},t.prototype.Ot=function(e){this.it?this.it(e):"msg"in e&&"undefined"!=typeof console&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))},t.prototype.Lt=function(){var e=this;this.tryAuth(),o.forEach(this.Je,function(t,n){o.forEach(n,function(t,n){e.mt(n)})});for(var t=0;t0,"Requires a non-empty array")}return e.prototype.trigger=function(e){for(var t=[],n=1;n0&&(this.rn=r.setTimeoutNonBlocking(function(){e.rn=null,e.nn||(e.Yt&&e.Yt.bytesReceived>102400?(e.de("Connection exceeded healthy timeout but has received "+e.Yt.bytesReceived+" bytes. Marking connection healthy."),e.nn=!0,e.Yt.markConnectionHealthy()):e.Yt&&e.Yt.bytesSent>10240?e.de("Connection exceeded healthy timeout but has sent "+e.Yt.bytesSent+" bytes. Leaving connection alive."):(e.de("Closing unhealthy connection after timeout."),e.close()))},Math.floor(o)))},e.prototype.Xt=function(){return"c:"+this.id+":"+this.connectionCount++},e.prototype.$t=function(e){var t=this;return function(n){e===t.Yt?t.in(n):e===t.tn?(t.de("Secondary connection lost."),t.an()):t.de("closing an old connection")}},e.prototype.Jt=function(e){var t=this;return function(n){2!=t.Ht&&(e===t.en?t.sn(n):e===t.tn?t.un(n):t.de("message on old connection"))}},e.prototype.sendRequest=function(e){var t={t:"d",d:e};this.ln(t)},e.prototype.tryCleanupConnection=function(){this.Zt===this.tn&&this.en===this.tn&&(this.de("cleaning up and promoting a connection: "+this.tn.connId),this.Yt=this.tn,this.tn=null)},e.prototype.hn=function(e){if("t"in e){var t=e.t;"a"===t?this.cn():"r"===t?(this.de("Got a reset on secondary, closing it"),this.tn.close(),this.Zt!==this.tn&&this.en!==this.tn||this.close()):"o"===t&&(this.de("got pong on secondary."),this.pn--,this.cn())}},e.prototype.un=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);if("c"==t)this.hn(n);else{if("d"!=t)throw Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}},e.prototype.cn=function(){this.pn<=0?(this.de("Secondary connection is healthy."),this.nn=!0,this.tn.markConnectionHealthy(),this.dn()):(this.de("sending ping on secondary."),this.tn.send({t:"c",d:{t:"p",d:{}}}))},e.prototype.dn=function(){this.tn.start(),this.de("sending client ack on secondary"),this.tn.send({t:"c",d:{t:"a",d:{}}}),this.de("Ending transmission on primary"),this.Yt.send({t:"c",d:{t:"n",d:{}}}),this.Zt=this.tn,this.tryCleanupConnection()},e.prototype.sn=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);"c"==t?this.fn(n):"d"==t&&this.wt(n)},e.prototype.wt=function(e){this._n(),this.Ut(e)},e.prototype._n=function(){this.nn||--this.zt<=0&&(this.de("Primary connection is healthy."),this.nn=!0,this.Yt.markConnectionHealthy())},e.prototype.fn=function(e){var t=r.requireKey("t",e);if("d"in e){var n=e.d;if("h"===t)this.yn(n);else if("n"===t){this.de("recvd end transmission on primary"),this.en=this.tn;for(var i=0;idocument.domain="'+document.domain+'";<\/script>');var h=""+u+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(h),this.myIFrame.doc.close()}catch(e){r.log("frame writing exception"),e.stack&&r.log(e.stack),r.log(e)}}}return e.Dn=function(){var e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||r.log("No IE domain setting required")}catch(n){var t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e},e.prototype.close=function(){var n=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==n.myIFrame&&(document.body.removeChild(n.myIFrame),n.myIFrame=null)},Math.floor(0))),l.isNodeSdk()&&this.myID){var r={};r[t.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM]="t",r[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,r[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW;var i=this.urlFn(r);e.nodeRestRequest(i)}var o=this.onDisconnect;o&&(this.onDisconnect=null,o())},e.prototype.startLongPoll=function(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.Mn(););},e.prototype.Mn=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var e={};e[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,e[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW,e[t.FIREBASE_LONGPOLL_SERIAL_PARAM]=this.currentSerial;for(var n=this.urlFn(e),r="",i=0;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+r.length<=1870;){var o=this.pendingSegs.shift();r=r+"&"+t.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM+i+"="+o.seg+"&"+t.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET+i+"="+o.ts+"&"+t.FIREBASE_LONGPOLL_DATA_PARAM+i+"="+o.d,i++}return n+=r,this.Ln(n,this.currentSerial),!0}return!1},e.prototype.enqueueSegment=function(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.Mn()},e.prototype.Ln=function(e,t){var n=this;this.outstandingRequests.add(t,1);var r=function(){n.outstandingRequests.remove(t),n.Mn()},i=setTimeout(r,Math.floor(25e3)),o=function(){clearTimeout(i),r()};this.addTag(e,o)},e.prototype.addTag=function(e,t){var n=this;l.isNodeSdk()?this.doNodeLongPoll(e,t):setTimeout(function(){try{if(!n.sendNewPolls)return;var i=n.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){var e=i.readyState;e&&"loaded"!==e&&"complete"!==e||(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=function(){r.log("Long-poll script failed to load: "+e),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(i)}catch(e){}},Math.floor(1))},e}();t.FirebaseIFrameScriptHolder=c},function(e,t,n){"use strict";(function(e){function r(e){d=e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),o=n(0),a=n(1),s=n(25),u=n(13),l=n(0),h=n(12),c=n(0),p=n(0),d=null;"undefined"!=typeof MozWebSocket?d=MozWebSocket:"undefined"!=typeof WebSocket&&(d=WebSocket),t.setWebSocketImpl=r;var f=function(){function t(e,n,r,i){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.de=a.logWrapper(this.connId),this.$=s.StatsManager.getCollection(n),this.connURL=t.Fn(n,r,i)}return t.Fn=function(e,t,n){var r={};return r[u.VERSION_PARAM]=u.PROTOCOL_VERSION,!p.isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf(u.FORGE_DOMAIN)&&(r[u.REFERER_PARAM]=u.FORGE_REF),t&&(r[u.TRANSPORT_SESSION_PARAM]=t),n&&(r[u.LAST_SESSION_PARAM]=n),e.connectionURL(u.WEBSOCKET,r)},t.prototype.open=function(t,n){var r=this;this.onDisconnect=n,this.onMessage=t,this.de("Websocket connecting to "+this.connURL),this.bn=!1,h.PersistentStorage.set("previous_websocket_failure",!0);try{if(p.isNodeSdk()){var o=l.CONSTANTS.NODE_ADMIN?"AdminNode":"Node",a={headers:{"User-Agent":"Firebase/"+u.PROTOCOL_VERSION+"/"+i.default.SDK_VERSION+"/"+e.platform+"/"+o}},s=e.env,c=0==this.connURL.indexOf("wss://")?s.HTTPS_PROXY||s.https_proxy:s.HTTP_PROXY||s.http_proxy;c&&(a.proxy={origin:c}),this.mySock=new d(this.connURL,[],a)}else this.mySock=new d(this.connURL)}catch(e){this.de("Error instantiating WebSocket.");var f=e.message||e.data;return f&&this.de(f),void this.wn()}this.mySock.onopen=function(){r.de("Websocket connected."),r.bn=!0},this.mySock.onclose=function(){r.de("Websocket connection was disconnected."),r.mySock=null,r.wn()},this.mySock.onmessage=function(e){r.handleIncomingFrame(e)},this.mySock.onerror=function(e){r.de("WebSocket error. Closing connection.");var t=e.message||e.data;t&&r.de(t),r.wn()}},t.prototype.start=function(){},t.forceDisallow=function(){t.On=!0},t.isAvailable=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=/Android ([0-9]{0,}\.[0-9]{0,})/,r=navigator.userAgent.match(n);r&&r.length>1&&parseFloat(r[1])<4.4&&(e=!0)}return!e&&null!==d&&!t.On},t.previouslyFailed=function(){return h.PersistentStorage.isInMemoryStorage||!0===h.PersistentStorage.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){h.PersistentStorage.remove("previous_websocket_failure")},t.prototype.xn=function(e){if(this.frames.push(e),this.frames.length==this.totalFrames){var t=this.frames.join("");this.frames=null;var n=c.jsonEval(t);this.onMessage(n)}},t.prototype.kn=function(e){this.totalFrames=e,this.frames=[]},t.prototype.Wn=function(e){if(o.assert(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=+e;if(!isNaN(t))return this.kn(t),null}return this.kn(1),e},t.prototype.handleIncomingFrame=function(e){if(null!==this.mySock){var t=e.data;if(this.bytesReceived+=t.length,this.$.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.xn(t);else{var n=this.Wn(t);null!==n&&this.xn(n)}}},t.prototype.send=function(e){this.resetKeepAlive();var t=c.stringify(e);this.bytesSent+=t.length,this.$.incrementCounter("bytes_sent",t.length);var n=a.splitStringBySize(t,16384);n.length>1&&this.jn(n.length+"");for(var r=0;r=0;a--)s[a]=e.charAt(i%64),i=Math.floor(i/64);r.assert(0===i,"Cannot push at time == 0");var u=s.join("");if(o){for(a=11;a>=0&&63===n[a];a--)n[a]=0;n[a]++}else for(a=0;a<12;a++)n[a]=Math.floor(64*Math.random());for(a=0;a<12;a++)u+=e.charAt(n[a]);return r.assert(20===u.length,"nextPushId: Length should be 20."),u}}()},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(22),i=n(85),o=n(0),a=n(0),s=function(){function e(e,t,n){this.Xn=e,this.zn=t,this.Jn=n}return e.prototype.respondsTo=function(e){return"value"===e},e.prototype.createEvent=function(e,t){var n=t.getQueryParams().getIndex();return new i.DataEvent("value",this,new r.DataSnapshot(e.snapshotNode,t.getRef(),n))},e.prototype.getEventRunner=function(e){var t=this.Jn;if("cancel"===e.getEventType()){a.assert(this.zn,"Raising a cancel event on a listener with no cancel callback");var n=this.zn;return function(){n.call(t,e.error)}}var r=this.Xn;return function(){r.call(t,e.snapshot)}},e.prototype.createCancelEvent=function(e,t){return this.zn?new i.CancelEvent(this,e,t):null},e.prototype.matches=function(t){return t instanceof e&&(!t.Xn||!this.Xn||t.Xn===this.Xn&&t.Jn===this.Jn)},e.prototype.hasAnyCallback=function(){return null!==this.Xn},e}();t.ValueEventRegistration=s;var u=function(){function e(e,t,n){this.$n=e,this.zn=t,this.Jn=n}return e.prototype.respondsTo=function(e){var t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,o.contains(this.$n,t)},e.prototype.createCancelEvent=function(e,t){return this.zn?new i.CancelEvent(this,e,t):null},e.prototype.createEvent=function(e,t){a.assert(null!=e.childName,"Child events should have a childName.");var n=t.getRef().child(e.childName),o=t.getQueryParams().getIndex();return new i.DataEvent(e.type,this,new r.DataSnapshot(e.snapshotNode,n,o),e.prevName)},e.prototype.getEventRunner=function(e){var t=this.Jn;if("cancel"===e.getEventType()){a.assert(this.zn,"Raising a cancel event on a listener with no cancel callback");var n=this.zn;return function(){n.call(t,e.error)}}var r=this.$n[e.eventType];return function(){r.call(t,e.snapshot,e.prevName)}},e.prototype.matches=function(t){if(t instanceof e){if(!this.$n||!t.$n)return!0;if(this.Jn===t.Jn){var n=o.getCount(t.$n);if(n===o.getCount(this.$n)){if(1===n){var r=o.getAnyKey(t.$n),i=o.getAnyKey(this.$n);return!(i!==r||t.$n[r]&&this.$n[i]&&t.$n[r]!==this.$n[i])}return o.every(this.$n,function(e,n){return t.$n[e]===n})}}}return!1},e.prototype.hasAnyCallback=function(){return null!==this.$n},e}();t.ChildEventRegistration=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=function(){function e(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}return e.prototype.getPath=function(){var e=this.snapshot.getRef();return"value"===this.eventType?e.path:e.getParent().path},e.prototype.getEventType=function(){return this.eventType},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.getPath()+":"+this.eventType+":"+r.stringify(this.snapshot.exportVal())},e}();t.DataEvent=i;var o=function(){function e(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}return e.prototype.getPath=function(){return this.path},e.prototype.getEventType=function(){return"cancel"},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.path+":cancel"},e}();t.CancelEvent=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(87),a=n(4),s=n(0),u=n(23),l=n(88),h=n(89),c=n(8),p=n(46),d=n(2),f=n(47),_=n(95),y=function(){function e(e){this.Zn=e,this.er=u.ImmutableTree.Empty,this.tr=new _.WriteTree,this.nr={},this.rr={}}return e.prototype.applyUserOverwrite=function(e,t,n,r){return this.tr.addOverwrite(e,t,n,r),r?this.ir(new p.Overwrite(c.OperationSource.User,e,t)):[]},e.prototype.applyUserMerge=function(e,t,n){this.tr.addMerge(e,t,n);var r=u.ImmutableTree.fromObject(t);return this.ir(new h.Merge(c.OperationSource.User,e,r))},e.prototype.ackUserWrite=function(e,t){void 0===t&&(t=!1);var n=this.tr.getWrite(e);if(this.tr.removeWrite(e)){var r=u.ImmutableTree.Empty;return null!=n.snap?r=r.set(d.Path.Empty,!0):s.forEach(n.children,function(e,t){r=r.set(new d.Path(e),t)}),this.ir(new o.AckUserWrite(n.path,r,t))}return[]},e.prototype.applyServerOverwrite=function(e,t){return this.ir(new p.Overwrite(c.OperationSource.Server,e,t))},e.prototype.applyServerMerge=function(e,t){var n=u.ImmutableTree.fromObject(t);return this.ir(new h.Merge(c.OperationSource.Server,e,n))},e.prototype.applyListenComplete=function(e){return this.ir(new l.ListenComplete(c.OperationSource.Server,e))},e.prototype.applyTaggedQueryOverwrite=function(t,n,r){var i=this.or(r);if(null!=i){var o=e.ar(i),a=o.path,s=o.queryId,u=d.Path.relativePath(a,t),l=new p.Overwrite(c.OperationSource.forServerTaggedQuery(s),u,n);return this.sr(a,l)}return[]},e.prototype.applyTaggedQueryMerge=function(t,n,r){var i=this.or(r);if(i){var o=e.ar(i),a=o.path,s=o.queryId,l=d.Path.relativePath(a,t),p=u.ImmutableTree.fromObject(n),f=new h.Merge(c.OperationSource.forServerTaggedQuery(s),l,p);return this.sr(a,f)}return[]},e.prototype.applyTaggedListenComplete=function(t,n){var r=this.or(n);if(r){var i=e.ar(r),o=i.path,a=i.queryId,s=d.Path.relativePath(o,t),u=new l.ListenComplete(c.OperationSource.forServerTaggedQuery(a),s);return this.sr(o,u)}return[]},e.prototype.addEventRegistration=function(t,n){var i=t.path,o=null,s=!1;this.er.foreachOnPath(i,function(e,t){var n=d.Path.relativePath(e,i);o=o||t.getCompleteServerCache(n),s=s||t.hasCompleteView()});var u=this.er.get(i);u?(s=s||u.hasCompleteView(),o=o||u.getCompleteServerCache(d.Path.Empty)):(u=new f.SyncPoint,this.er=this.er.set(i,u));var l;null!=o?l=!0:(l=!1,o=a.ChildrenNode.EMPTY_NODE,this.er.subtree(i).foreachChild(function(e,t){var n=t.getCompleteServerCache(d.Path.Empty);n&&(o=o.updateImmediateChild(e,n))}));var h=u.viewExistsForQuery(t);if(!h&&!t.getQueryParams().loadsAllData()){var c=e.ur(t);r.assert(!(c in this.rr),"View does not exist, but we have a tag");var p=e.lr();this.rr[c]=p,this.nr["_"+p]=c}var _=this.tr.childWrites(i),y=u.addEventRegistration(t,n,_,o,l);if(!h&&!s){var v=u.viewForQuery(t);y=y.concat(this.hr(t,v))}return y},e.prototype.removeEventRegistration=function(t,n,r){var i=this,o=t.path,a=this.er.get(o),s=[];if(a&&("default"===t.queryIdentifier()||a.viewExistsForQuery(t))){var u=a.removeEventRegistration(t,n,r);a.isEmpty()&&(this.er=this.er.remove(o));var l=u.removed;s=u.events;var h=-1!==l.findIndex(function(e){return e.getQueryParams().loadsAllData()}),c=this.er.findOnPath(o,function(e,t){return t.hasCompleteView()});if(h&&!c){var p=this.er.subtree(o);if(!p.isEmpty())for(var d=this.cr(p),f=0;f0&&!r&&(h?this.Zn.stopListening(e.dr(t),null):l.forEach(function(t){var n=i.rr[e.ur(t)];i.Zn.stopListening(e.dr(t),n)})),this._r(l)}return s},e.prototype.calcCompleteEventCache=function(e,t){var n=this.tr,r=this.er.findOnPath(e,function(t,n){var r=d.Path.relativePath(t,e),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(e,r,t,!0)},e.prototype.cr=function(e){return e.fold(function(e,t,n){if(t&&t.hasCompleteView())return[t.getCompleteView()];var r=[];return t&&(r=t.getQueryViews()),s.forEach(n,function(e,t){r=r.concat(t)}),r})},e.prototype._r=function(t){for(var n=0;n0||!e.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(a.Change.valueChange(t.getCompleteEventSnap()))}},e.prototype.Lr=function(e,t,n,r,o){var a=e.getEventCache();if(null!=n.shadowingWrite(t))return e;var u=void 0,l=void 0;if(t.isEmpty())if(i.assert(e.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),e.getServerCache().isFiltered()){var h=e.getCompleteServerSnap(),c=h instanceof s.ChildrenNode?h:s.ChildrenNode.EMPTY_NODE,p=n.calcCompleteEventChildren(c);u=this.Sr.updateFullNode(e.getEventCache().getNode(),p,o)}else{var d=n.calcCompleteEventCache(e.getCompleteServerSnap());u=this.Sr.updateFullNode(e.getEventCache().getNode(),d,o)}else{var f=t.getFront();if(".priority"==f){i.assert(1==t.getLength(),"Can't have a priority with additional path components");var _=a.getNode();l=e.getServerCache().getNode();var y=n.calcEventCacheAfterServerOverwrite(t,_,l);u=null!=y?this.Sr.updatePriority(_,y):a.getNode()}else{var v=t.popFront(),g=void 0;if(a.isCompleteForChild(f)){l=e.getServerCache().getNode();var m=n.calcEventCacheAfterServerOverwrite(t,a.getNode(),l);g=null!=m?a.getNode().getImmediateChild(f).updateChild(v,m):a.getNode().getImmediateChild(f)}else g=n.calcCompleteChild(f,e.getServerCache());u=null!=g?this.Sr.updateChild(a.getNode(),f,g,v,r,o):a.getNode()}}return e.updateEventSnap(u,a.isFullyInitialized()||t.isEmpty(),this.Sr.filtersNodes())},e.prototype.wr=function(e,t,n,r,i,o,a){var s,u=e.getServerCache(),l=o?this.Sr:this.Sr.getIndexedFilter();if(t.isEmpty())s=l.updateFullNode(u.getNode(),n,null);else if(l.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(t,n);s=l.updateFullNode(u.getNode(),h,null)}else{var p=t.getFront();if(!u.isCompleteForPath(t)&&t.getLength()>1)return e;var d=t.popFront(),f=u.getNode().getImmediateChild(p),_=f.updateChild(d,n);s=".priority"==p?l.updatePriority(u.getNode(),_):l.updateChild(u.getNode(),p,_,d,c.NO_COMPLETE_CHILD_SOURCE,null)}var y=e.updateServerSnap(s,u.isFullyInitialized()||t.isEmpty(),l.filtersNodes()),v=new c.WriteTreeCompleteChildSource(r,y,i);return this.Lr(y,t,r,v,a)},e.prototype.Tr=function(e,t,n,r,i,o){var a,u,l=e.getEventCache(),h=new c.WriteTreeCompleteChildSource(r,e,i);if(t.isEmpty())u=this.Sr.updateFullNode(e.getEventCache().getNode(),n,o),a=e.updateEventSnap(u,!0,this.Sr.filtersNodes());else{var p=t.getFront();if(".priority"===p)u=this.Sr.updatePriority(e.getEventCache().getNode(),n),a=e.updateEventSnap(u,l.isFullyInitialized(),l.isFiltered());else{var d=t.popFront(),f=l.getNode().getImmediateChild(p),_=void 0;if(d.isEmpty())_=n;else{var y=h.getCompleteChild(p);_=null!=y?".priority"===d.getBack()&&y.getChild(d.parent()).isEmpty()?y:y.updateChild(d,n):s.ChildrenNode.EMPTY_NODE}if(f.equals(_))a=e;else{var v=this.Sr.updateChild(l.getNode(),p,_,d,h,o);a=e.updateEventSnap(v,l.isFullyInitialized(),this.Sr.filtersNodes())}}}return a},e.Fr=function(e,t){return e.getEventCache().isCompleteForChild(t)},e.prototype.Ir=function(t,n,r,i,o,a){var s=this,u=t;return r.foreach(function(r,l){var h=n.child(r);e.Fr(t,h.getFront())&&(u=s.Tr(u,h,l,i,o,a))}),r.foreach(function(r,l){var h=n.child(r);e.Fr(t,h.getFront())||(u=s.Tr(u,h,l,i,o,a))}),u},e.prototype.xr=function(e,t){return t.foreach(function(t,n){e=e.updateChild(t,n)}),e},e.prototype.Rr=function(e,t,n,r,i,o,a){var s=this;if(e.getServerCache().getNode().isEmpty()&&!e.getServerCache().isFullyInitialized())return e;var u,c=e;u=t.isEmpty()?n:l.ImmutableTree.Empty.setTree(t,n);var p=e.getServerCache().getNode();return u.children.inorderTraversal(function(t,n){if(p.hasChild(t)){var u=e.getServerCache().getNode().getImmediateChild(t),l=s.xr(u,n);c=s.wr(c,new h.Path(t),l,r,i,o,a)}}),u.children.inorderTraversal(function(t,n){var u=!e.getServerCache().isCompleteForChild(t)&&null==n.value;if(!p.hasChild(t)&&!u){var l=e.getServerCache().getNode().getImmediateChild(t),d=s.xr(l,n);c=s.wr(c,new h.Path(t),d,r,i,o,a)}}),c},e.prototype.Ar=function(e,t,n,r,i,o){if(null!=r.shadowingWrite(t))return e;var a=e.getServerCache().isFiltered(),s=e.getServerCache();if(null!=n.value){if(t.isEmpty()&&s.isFullyInitialized()||s.isCompleteForPath(t))return this.wr(e,t,s.getNode().getChild(t),r,i,a,o);if(t.isEmpty()){var c=l.ImmutableTree.Empty;return s.getNode().forEachChild(u.KEY_INDEX,function(e,t){c=c.set(new h.Path(e),t)}),this.Rr(e,t,c,r,i,a,o)}return e}var p=l.ImmutableTree.Empty;return n.foreach(function(e,n){var r=t.child(e);s.isCompleteForPath(r)&&(p=p.set(e,s.getNode().getChild(r)))}),this.Rr(e,t,p,r,i,a,o)},e.prototype.Dr=function(e,t,n,r){var i=e.getServerCache(),o=e.updateServerSnap(i.getNode(),i.isFullyInitialized()||t.isEmpty(),i.isFiltered());return this.Lr(o,t,n,c.NO_COMPLETE_CHILD_SOURCE,r)},e.prototype.Or=function(e,t,n,r,o){var a;if(null!=n.shadowingWrite(t))return e;var u=new c.WriteTreeCompleteChildSource(n,e,r),l=e.getEventCache().getNode(),p=void 0;if(t.isEmpty()||".priority"===t.getFront()){var d=void 0;if(e.getServerCache().isFullyInitialized())d=n.calcCompleteEventCache(e.getCompleteServerSnap());else{var f=e.getServerCache().getNode();i.assert(f instanceof s.ChildrenNode,"serverChildren would be complete if leaf node"),d=n.calcCompleteEventChildren(f)}d=d,p=this.Sr.updateFullNode(l,d,o)}else{var _=t.getFront(),y=n.calcCompleteChild(_,e.getServerCache());null==y&&e.getServerCache().isCompleteForChild(_)&&(y=l.getImmediateChild(_)),p=null!=y?this.Sr.updateChild(l,_,y,t.popFront(),u,o):e.getEventCache().getNode().hasChild(_)?this.Sr.updateChild(l,_,s.ChildrenNode.EMPTY_NODE,t.popFront(),u,o):l,p.isEmpty()&&e.getServerCache().isFullyInitialized()&&(a=n.calcCompleteEventCache(e.getCompleteServerSnap()),a.isLeafNode()&&(p=this.Sr.updateFullNode(p,a,o)))}return a=e.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(h.Path.Empty),e.updateEventSnap(p,a,this.Sr.filtersNodes())},e}();t.ViewProcessor=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(9),o=n(0),a=function(){function e(){this.kr={}}return e.prototype.trackChildChange=function(e){var t=e.type,n=e.childName;o.assert(t==i.Change.CHILD_ADDED||t==i.Change.CHILD_CHANGED||t==i.Change.CHILD_REMOVED,"Only child changes supported for tracking"),o.assert(".priority"!==n,"Only non-priority child changes can be tracked.");var a=r.safeGet(this.kr,n);if(a){var s=a.type;if(t==i.Change.CHILD_ADDED&&s==i.Change.CHILD_REMOVED)this.kr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.snapshotNode);else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_ADDED)delete this.kr[n];else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_CHANGED)this.kr[n]=i.Change.childRemovedChange(n,a.oldSnap);else if(t==i.Change.CHILD_CHANGED&&s==i.Change.CHILD_ADDED)this.kr[n]=i.Change.childAddedChange(n,e.snapshotNode);else{if(t!=i.Change.CHILD_CHANGED||s!=i.Change.CHILD_CHANGED)throw o.assertionError("Illegal combination of changes: "+e+" occurred after "+a);this.kr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.oldSnap)}}else this.kr[n]=e},e.prototype.getChanges=function(){return r.getValues(this.kr)},e}();t.ChildChangeAccumulator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(18),i=function(){function e(){}return e.prototype.getCompleteChild=function(e){return null},e.prototype.getChildAfterChild=function(e,t,n){return null},e}();t.Wr=i,t.NO_COMPLETE_CHILD_SOURCE=new i;var o=function(){function e(e,t,n){void 0===n&&(n=null),this.jr=e,this.Nr=t,this.Vr=n}return e.prototype.getCompleteChild=function(e){var t=this.Nr.getEventCache();if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.Vr?new r.CacheNode(this.Vr,!0,!1):this.Nr.getServerCache();return this.jr.calcCompleteChild(e,n)},e.prototype.getChildAfterChild=function(e,t,n){var r=null!=this.Vr?this.Vr:this.Nr.getCompleteServerSnap(),i=this.jr.calcIndexedSlice(r,t,1,n,e);return 0===i.length?null:i[0]},e}();t.WriteTreeCompleteChildSource=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(5),i=n(9),o=n(0),a=function(){function e(e){this.mr=e,this.me=this.mr.getQueryParams().getIndex()}return e.prototype.generateEventsForChanges=function(e,t,n){var r=this,o=[],a=[];return e.forEach(function(e){e.type===i.Change.CHILD_CHANGED&&r.me.indexedValueChanged(e.oldSnap,e.snapshotNode)&&a.push(i.Change.childMovedChange(e.childName,e.snapshotNode))}),this.Qr(o,i.Change.CHILD_REMOVED,e,n,t),this.Qr(o,i.Change.CHILD_ADDED,e,n,t),this.Qr(o,i.Change.CHILD_MOVED,a,n,t),this.Qr(o,i.Change.CHILD_CHANGED,e,n,t),this.Qr(o,i.Change.VALUE,e,n,t),o},e.prototype.Qr=function(e,t,n,r,i){var o=this,a=n.filter(function(e){return e.type===t});a.sort(this.qr.bind(this)),a.forEach(function(t){var n=o.Ur(t,i);r.forEach(function(r){r.respondsTo(t.type)&&e.push(r.createEvent(n,o.mr))})})},e.prototype.Ur=function(e,t){return"value"===e.type||"child_removed"===e.type?e:(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,this.me),e)},e.prototype.qr=function(e,t){if(null==e.childName||null==t.childName)throw o.assertionError("Should only compare child_ events.");var n=new r.NamedNode(e.childName,e.snapshotNode),i=new r.NamedNode(t.childName,t.snapshotNode);return this.me.compare(n,i)},e}();t.EventGenerator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(2),a=n(96),s=n(3),u=n(4),l=function(){function e(){this.Br=a.CompoundWrite.Empty,this.Hr=[],this.Gr=-1}return e.prototype.childWrites=function(e){return new h(e,this)},e.prototype.addOverwrite=function(e,t,n,r){i.assert(n>this.Gr,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.Hr.push({path:e,snap:t,writeId:n,visible:r}),r&&(this.Br=this.Br.addWrite(e,t)),this.Gr=n},e.prototype.addMerge=function(e,t,n){i.assert(n>this.Gr,"Stacking an older merge on top of newer ones"),this.Hr.push({path:e,children:t,writeId:n,visible:!0}),this.Br=this.Br.addWrites(e,t),this.Gr=n},e.prototype.getWrite=function(e){for(var t=0;t=0,"removeWrite called with nonexistent writeId.");var o=this.Hr[n];this.Hr.splice(n,1);for(var a=o.visible,s=!1,u=this.Hr.length-1;a&&u>=0;){var l=this.Hr[u];l.visible&&(u>=n&&this.Kr(l,o.path)?a=!1:o.path.contains(l.path)&&(s=!0)),u--}if(a){if(s)return this.Yr(),!0;if(o.snap)this.Br=this.Br.removeWrite(o.path);else{var h=o.children;r.forEach(h,function(e){t.Br=t.Br.removeWrite(o.path.child(e))})}return!0}return!1},e.prototype.getCompleteWriteData=function(e){return this.Br.getCompleteNode(e)},e.prototype.calcCompleteEventCache=function(t,n,r,i){if(r||i){var a=this.Br.childCompoundWrite(t);if(!i&&a.isEmpty())return n;if(i||null!=n||a.hasCompleteWrite(o.Path.Empty)){var s=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(e.path.contains(t)||t.contains(e.path))},l=e.Xr(this.Hr,s,t),h=n||u.ChildrenNode.EMPTY_NODE;return l.apply(h)}return null}var c=this.Br.getCompleteNode(t);if(null!=c)return c;var p=this.Br.childCompoundWrite(t);if(p.isEmpty())return n;if(null!=n||p.hasCompleteWrite(o.Path.Empty)){var h=n||u.ChildrenNode.EMPTY_NODE;return p.apply(h)}return null},e.prototype.calcCompleteEventChildren=function(e,t){var n=u.ChildrenNode.EMPTY_NODE,r=this.Br.getCompleteNode(e);if(r)return r.isLeafNode()||r.forEachChild(s.PRIORITY_INDEX,function(e,t){n=n.updateImmediateChild(e,t)}),n;if(t){var i=this.Br.childCompoundWrite(e);return t.forEachChild(s.PRIORITY_INDEX,function(e,t){var r=i.childCompoundWrite(new o.Path(e)).apply(t);n=n.updateImmediateChild(e,r)}),i.getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n}return this.Br.childCompoundWrite(e).getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n},e.prototype.calcEventCacheAfterServerOverwrite=function(e,t,n,r){i.assert(n||r,"Either existingEventSnap or existingServerSnap must exist");var o=e.child(t);if(this.Br.hasCompleteWrite(o))return null;var a=this.Br.childCompoundWrite(o);return a.isEmpty()?r.getChild(t):a.apply(r.getChild(t))},e.prototype.calcCompleteChild=function(e,t,n){var r=e.child(t),i=this.Br.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(t)?this.Br.childCompoundWrite(r).apply(n.getNode().getImmediateChild(t)):null},e.prototype.shadowingWrite=function(e){return this.Br.getCompleteNode(e)},e.prototype.calcIndexedSlice=function(e,t,n,r,i,a){var s,u=this.Br.childCompoundWrite(e),l=u.getCompleteNode(o.Path.Empty);if(null!=l)s=l;else{if(null==t)return[];s=u.apply(t)}if(s=s.withIndex(a),s.isEmpty()||s.isLeafNode())return[];for(var h=[],c=a.getCompare(),p=i?s.getReverseIteratorFrom(n,a):s.getIteratorFrom(n,a),d=p.getNext();d&&h.length0?this.Gr=this.Hr[this.Hr.length-1].writeId:this.Gr=-1},e.zr=function(e){return e.visible},e.Xr=function(e,t,n){for(var s=a.CompoundWrite.Empty,u=0;u0&&r.contains(e.ri,t)&&(n[t]=i,o=!0)}),o&&this.Z.reportStats(n),i.setTimeoutNonBlocking(this.ii.bind(this),Math.floor(2*Math.random()*3e5))},e}();t.StatsReporter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(){this.oi=[],this.ai=0}return e.prototype.queueEvents=function(e){for(var t=null,n=0;n0)return this.ci[0];throw Error("No transports available")},e.prototype.upgradeTransport=function(){return this.ci.length>1?this.ci[1]:null},e}();t.TransportManager=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(e){this.Ut=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return e.prototype.closeAfter=function(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse=200&&h.status<300){try{e=a.jsonEval(h.responseText)}catch(e){o.warn("Failed to parse JSON response for "+l+": "+h.responseText)}n(null,e)}else 401!==h.status&&404!==h.status&&o.warn("Got unsuccessful REST response for "+l+" Status: "+h.status),n(h.status);n=null}},h.open("GET",l,!0),h.send()})},t}(l.ServerActions);t.ReadonlyRestClient=h},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(10),a=n(3),s=n(38),u=n(42),l=n(24),h=n(108),c=n(56),p=n(0),d=function(){function e(){this.fi=!1,this._i=!1,this.yi=!1,this.vi=!1,this.gi=!1,this.mi=0,this.Ci="",this.Ei=null,this.Ni="",this.Pi=null,this.bi="",this.me=a.PRIORITY_INDEX}return e.prototype.hasStart=function(){return this._i},e.prototype.isViewFromLeft=function(){return""===this.Ci?this._i:this.Ci===e.Si.VIEW_FROM_LEFT},e.prototype.getIndexStartValue=function(){return r.assert(this._i,"Only valid if start has been set"),this.Ei},e.prototype.getIndexStartName=function(){return r.assert(this._i,"Only valid if start has been set"),this.yi?this.Ni:i.MIN_NAME},e.prototype.hasEnd=function(){return this.vi},e.prototype.getIndexEndValue=function(){return r.assert(this.vi,"Only valid if end has been set"),this.Pi},e.prototype.getIndexEndName=function(){return r.assert(this.vi,"Only valid if end has been set"),this.gi?this.bi:i.MAX_NAME},e.prototype.hasLimit=function(){return this.fi},e.prototype.hasAnchoredLimit=function(){return this.fi&&""!==this.Ci},e.prototype.getLimit=function(){return r.assert(this.fi,"Only valid if limit has been set"),this.mi},e.prototype.getIndex=function(){return this.me},e.prototype.Ti=function(){var t=new e;return t.fi=this.fi,t.mi=this.mi,t._i=this._i,t.Ei=this.Ei,t.yi=this.yi,t.Ni=this.Ni,t.vi=this.vi,t.Pi=this.Pi,t.gi=this.gi,t.bi=this.bi,t.me=this.me,t.Ci=this.Ci,t},e.prototype.limit=function(e){var t=this.Ti();return t.fi=!0,t.mi=e,t.Ci="",t},e.prototype.limitToFirst=function(t){var n=this.Ti();return n.fi=!0,n.mi=t,n.Ci=e.Si.VIEW_FROM_LEFT,n},e.prototype.limitToLast=function(t){var n=this.Ti();return n.fi=!0,n.mi=t,n.Ci=e.Si.VIEW_FROM_RIGHT,n},e.prototype.startAt=function(e,t){var n=this.Ti();return n._i=!0,void 0===e&&(e=null),n.Ei=e,null!=t?(n.yi=!0,n.Ni=t):(n.yi=!1,n.Ni=""),n},e.prototype.endAt=function(e,t){var n=this.Ti();return n.vi=!0,void 0===e&&(e=null),n.Pi=e,void 0!==t?(n.gi=!0,n.bi=t):(n.gi=!1,n.bi=""),n},e.prototype.orderBy=function(e){var t=this.Ti();return t.me=e,t},e.prototype.getQueryObject=function(){var t=e.Si,n={};if(this._i&&(n[t.INDEX_START_VALUE]=this.Ei,this.yi&&(n[t.INDEX_START_NAME]=this.Ni)),this.vi&&(n[t.INDEX_END_VALUE]=this.Pi,this.gi&&(n[t.INDEX_END_NAME]=this.bi)),this.fi){n[t.LIMIT]=this.mi;var r=this.Ci;""===r&&(r=this.isViewFromLeft()?t.VIEW_FROM_LEFT:t.VIEW_FROM_RIGHT),n[t.VIEW_FROM]=r}return this.me!==a.PRIORITY_INDEX&&(n[t.INDEX]=""+this.me),n},e.prototype.loadsAllData=function(){return!(this._i||this.vi||this.fi)},e.prototype.isDefault=function(){return this.loadsAllData()&&this.me==a.PRIORITY_INDEX},e.prototype.getNodeFilter=function(){return this.loadsAllData()?new l.IndexedFilter(this.getIndex()):this.hasLimit()?new h.LimitedFilter(this):new c.RangedFilter(this)},e.prototype.toRestQueryStringParameters=function(){var t=e.wi,n={};if(this.isDefault())return n;var i;return this.me===a.PRIORITY_INDEX?i=t.PRIORITY_INDEX:this.me===s.VALUE_INDEX?i=t.VALUE_INDEX:this.me===o.KEY_INDEX?i=t.KEY_INDEX:(r.assert(this.me instanceof u.PathIndex,"Unrecognized index type!"),i=""+this.me),n[t.ORDER_BY]=p.stringify(i),this._i&&(n[t.START_AT]=p.stringify(this.Ei),this.yi&&(n[t.START_AT]+=","+p.stringify(this.Ni))),this.vi&&(n[t.END_AT]=p.stringify(this.Pi),this.gi&&(n[t.END_AT]+=","+p.stringify(this.bi))),this.fi&&(this.isViewFromLeft()?n[t.LIMIT_TO_FIRST]=this.mi:n[t.LIMIT_TO_LAST]=this.mi),n},e.Si={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},e.wi={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},e.DEFAULT=new e,e}();t.QueryParams=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(56),i=n(4),o=n(5),a=n(0),s=n(9),u=function(){function e(e){this.Ii=new r.RangedFilter(e),this.me=e.getIndex(),this.mi=e.getLimit(),this.Ri=!e.isViewFromLeft()}return e.prototype.updateChild=function(e,t,n,r,a,s){return this.Ii.matches(new o.NamedNode(t,n))||(n=i.ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()=0)return null!=u&&u.trackChildChange(s.Change.childChangedChange(t,n,_)),c.updateImmediateChild(t,n);null!=u&&u.trackChildChange(s.Change.childRemovedChange(t,_));var g=c.updateImmediateChild(t,i.ChildrenNode.EMPTY_NODE);return null!=y&&this.Ii.matches(y)?(null!=u&&u.trackChildChange(s.Change.childAddedChange(y.name,y.node)),g.updateImmediateChild(y.name,y.node)):g}return n.isEmpty()?e:f&&l(d,p)>=0?(null!=u&&(u.trackChildChange(s.Change.childRemovedChange(d.name,d.node)),u.trackChildChange(s.Change.childAddedChange(t,n))),c.updateImmediateChild(t,n).updateImmediateChild(d.name,i.ChildrenNode.EMPTY_NODE)):e},e}();t.LimitedFilter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i=n(0),o=n(21),a=n(22),s=n(2),u=n(110),l=n(3),h=n(1),c=n(43),p=n(7),d=n(0),f=n(11),_=n(4),y=n(17);!function(e){e[e.RUN=0]="RUN",e[e.SENT=1]="SENT",e[e.COMPLETED=2]="COMPLETED",e[e.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",e[e.NEEDS_ABORT=4]="NEEDS_ABORT"}(r=t.TransactionStatus||(t.TransactionStatus={})),y.Repo.Ai=25,y.Repo.prototype.ie=function(){this.Di=new u.Tree},y.Repo.prototype.startTransaction=function(e,t,n,s){this.de("transaction on "+e);var u=function(){},y=new o.Reference(this,e);y.on("value",u);var v=function(){y.off("value",u)},g={path:e,update:t,onComplete:n,status:null,order:h.LUIDGenerator(),applyLocally:s,retryCount:0,unwatcher:v,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},m=this.Mi(e);g.currentInputSnapshot=m;var C=g.update(m.val());if(void 0===C){if(g.unwatcher(),g.currentOutputSnapshotRaw=null,g.currentOutputSnapshotResolved=null,g.onComplete){var E=new a.DataSnapshot(g.currentInputSnapshot,new o.Reference(this,g.path),l.PRIORITY_INDEX);g.onComplete(null,!1,E)}}else{p.validateFirebaseData("transaction failed: Data returned ",C,g.path),g.status=r.RUN;var N=this.Di.subTree(e),P=N.getValue()||[];P.push(g),N.setValue(P);var b=void 0;"object"==typeof C&&null!==C&&d.contains(C,".priority")?(b=d.safeGet(C,".priority"),i.assert(p.isValidPriority(b),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):b=(this.ue.calcCompleteEventCache(e)||_.ChildrenNode.EMPTY_NODE).getPriority().val(),b=b;var S=this.generateServerValues(),T=f.nodeFromJSON(C,b),w=c.resolveDeferredValueSnapshot(T,S);g.currentOutputSnapshotRaw=T,g.currentOutputSnapshotResolved=w,g.currentWriteId=this.pe();var I=this.ue.applyUserOverwrite(e,w,g.currentWriteId,g.applyLocally);this.K.raiseEventsForChangedPath(e,I),this.Li()}},y.Repo.prototype.Mi=function(e,t){return this.ue.calcCompleteEventCache(e,t)||_.ChildrenNode.EMPTY_NODE},y.Repo.prototype.Li=function(e){var t=this;if(void 0===e&&(e=this.Di),e||this.Fi(e),null!==e.getValue()){var n=this.xi(e);i.assert(n.length>0,"Sending zero length transaction queue"),n.every(function(e){return e.status===r.RUN})&&this.ki(e.path(),n)}else e.hasChildren()&&e.forEachChild(function(e){t.Li(e)})},y.Repo.prototype.ki=function(e,t){for(var n=this,u=t.map(function(e){return e.currentWriteId}),c=this.Mi(e,u),p=c,d=c.hash(),f=0;f=y.Repo.Ai)E=!0,N="maxretry",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0));else{var P=this.Mi(m.path,v);m.currentInputSnapshot=P;var b=e[g].update(P.val());if(void 0!==b){p.validateFirebaseData("transaction failed: Data returned ",b,m.path);var S=f.nodeFromJSON(b),T="object"==typeof b&&null!=b&&d.contains(b,".priority");T||(S=S.updatePriority(P.getPriority()));var w=m.currentWriteId,I=this.generateServerValues(),R=c.resolveDeferredValueSnapshot(S,I);m.currentOutputSnapshotRaw=S,m.currentOutputSnapshotResolved=R,m.currentWriteId=this.pe(),v.splice(v.indexOf(w),1),u=u.concat(this.ue.applyUserOverwrite(m.path,R,m.currentWriteId,m.applyLocally)),u=u.concat(this.ue.ackUserWrite(w,!0))}else E=!0,N="nodata",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0))}if(this.K.raiseEventsForChangedPath(t,u),u=[],E&&(e[g].status=r.COMPLETED,function(e){setTimeout(e,Math.floor(0))}(e[g].unwatcher),e[g].onComplete))if("nodata"===N){var O=new o.Reference(this,e[g].path),A=e[g].currentInputSnapshot,D=new a.DataSnapshot(A,O,l.PRIORITY_INDEX);n.push(e[g].onComplete.bind(null,null,!1,D))}else n.push(e[g].onComplete.bind(null,Error(N),!1,null))}this.Fi(this.Di);for(var g=0;g0?n:null)}e.forEachChild(function(e){t.Fi(e)})},y.Repo.prototype.fe=function(e){var t=this,n=this.Wi(e).path(),r=this.Di.subTree(e);return r.forEachAncestor(function(e){t.Qi(e)}),this.Qi(r),r.forEachDescendant(function(e){t.Qi(e)}),n},y.Repo.prototype.Qi=function(e){var t=e.getValue();if(null!==t){for(var n=[],o=[],a=-1,s=0;s0},e.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},e.prototype.forEachChild=function(t){var n=this;o.forEach(this._e.children,function(r,i){t(new e(r,n,i))})},e.prototype.forEachDescendant=function(e,t,n){t&&!n&&e(this),this.forEachChild(function(t){t.forEachDescendant(e,!0,n)}),t&&n&&e(this)},e.prototype.forEachAncestor=function(e,t){for(var n=t?this:this.parent();null!==n;){if(e(n))return!0;n=n.parent()}return!1},e.prototype.forEachImmediateDescendantWithValue=function(e){this.forEachChild(function(t){null!==t.getValue()?e(t):t.forEachImmediateDescendantWithValue(e)})},e.prototype.path=function(){return new i.Path(null===this.Ui?this.qi:this.Ui.path()+"/"+this.qi)},e.prototype.name=function(){return this.qi},e.prototype.parent=function(){return this.Ui},e.prototype.Bi=function(){null!==this.Ui&&this.Ui.Hi(this.qi,this)},e.prototype.Hi=function(e,t){var n=t.isEmpty(),r=o.contains(this._e.children,e);n&&r?(delete this._e.children[e],this._e.childCount--,this.Bi()):n||r||(this._e.children[e]=t._e,this._e.childCount++,this.Bi())},e}();t.Tree=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(54),i=n(53);t.forceLongPolling=function(){r.WebSocketConnection.forceDisallow(),i.BrowserPollConnection.forceAllow()},t.forceWebSockets=function(){i.BrowserPollConnection.forceDisallow()},t.isWebSocketsAvailable=function(){return r.WebSocketConnection.isAvailable()},t.setSecurityDebugCallback=function(e,t){e.repo.J.it=t},t.stats=function(e,t){e.repo.stats(t)},t.statsIncrementCounter=function(e,t){e.repo.statsIncrementCounter(t)},t.dataUpdateCount=function(e){return e.repo.dataUpdateCount},t.interceptServerData=function(e,t){return e.repo.he(t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(34),i=n(50),o=n(26),a=n(52);t.DataConnection=i.PersistentConnection,i.PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},i.PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},t.RealTimeConnection=a.Connection,t.hijackHash=function(e){var t=i.PersistentConnection.prototype.put;return i.PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){i.PersistentConnection.prototype.put=t}},t.ConnectionTarget=r.RepoInfo,t.queryIdentifier=function(e){return e.queryIdentifier()},t.listens=function(e){return e.repo.J.Je},t.forceRestClient=function(e){o.RepoManager.getInstance().forceRestClient(e)}}],[78])}catch(e){throw Error("Cannot instantiate firebase-database.js - be sure to load firebase-app.js first.")} +try{webpackJsonpFirebase([0],[,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(0),a=n(0),s=n(0),u=n(0),l=n(14),h=n(0),c=n(22),p=new c.Logger("@firebase/database");t.LUIDGenerator=function(){var e=1;return function(){return e++}}(),t.sha1=function(e){var t=s.stringToByteArray(e),n=new a.Sha1;n.update(t);var r=n.digest();return o.base64.encodeByteArray(r)};var d=function(){for(var e=[],t=0;tn?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r},t.each=function(e,t){if(Array.isArray(e))for(var n=0;n=Math.pow(2,-1022)?(a=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=a+1023,o=Math.round(e*Math.pow(2,52-a)-Math.pow(2,52))):(i=0,o=Math.round(e/Math.pow(2,-1074)))),u=[],s=52;s;s-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(s=11;s;s-=1)u.push(i%2?1:0),i=Math.floor(i/2);u.push(n?1:0),u.reverse(),l=u.join("");var h="";for(s=0;s<64;s+=8){var c=parseInt(l.substr(s,8),2).toString(16);1===c.length&&(c="0"+c),h+=c}return h.toLowerCase()},t.isChromeExtensionContentScript=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},t.isWindowsStoreApp=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI},t.errorForServerCode=function(e,t){var n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==e?n="Client doesn't have permission to access the desired data.":"unavailable"==e&&(n="The service is unavailable");var r=Error(e+" at "+t.path+": "+n);return r.code=e.toUpperCase(),r},t.e=RegExp("^-?\\d{1,10}$"),t.tryParseInt=function(e){if(t.e.test(e)){var n=+e;if(n>=-2147483648&&n<=2147483647)return n}return null},t.exceptionGuard=function(e){try{e()}catch(e){setTimeout(function(){var n=e.stack||"";throw t.warn("Exception was thrown by user callback.",n),e},Math.floor(0))}},t.callUserCallback=function(e){for(var n=[],r=1;r=0},t.exportPropGetter=function(e,t,n){Object.defineProperty(e,t,{get:n})},t.setTimeoutNonBlocking=function(e,t){var n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}},,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=n(0),o=function(){function e(e,t){if(void 0===t){this.n=e.split("/");for(var n=0,r=0;r0&&(this.n[n]=this.n[r],n++);this.n.length=n,this.i=0}else this.n=e,this.i=t}return Object.defineProperty(e,"Empty",{get:function(){return new e("")},enumerable:!0,configurable:!0}),e.prototype.getFront=function(){return this.i>=this.n.length?null:this.n[this.i]},e.prototype.getLength=function(){return this.n.length-this.i},e.prototype.popFront=function(){var t=this.i;return t=this.n.length)return null;for(var t=[],n=this.i;n0&&n.push(i[r]);return new e(n,0)},e.prototype.isEmpty=function(){return this.i>=this.n.length},e.relativePath=function(t,n){var r=t.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return e.relativePath(t.popFront(),n.popFront());throw Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+t+")")},e.comparePaths=function(e,t){for(var n=e.slice(),i=t.slice(),o=0;oe.getLength())return!1;for(;t0&&(this.l+=1),this.u.push(e),this.l+=i.stringLength(e),this.f()},e.prototype.pop=function(){var e=this.u.pop();this.l-=i.stringLength(e),this.u.length>0&&(this.l-=1)},e.prototype.f=function(){if(this.l>e.MAX_PATH_LENGTH_BYTES)throw Error(this.o+"has a key path longer than "+e.MAX_PATH_LENGTH_BYTES+" bytes ("+this.l+").");if(this.u.length>e.MAX_PATH_DEPTH)throw Error(this.o+"path specified exceeds the maximum depth that can be written ("+e.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},e.prototype.toErrorString=function(){return 0==this.u.length?"":"in property '"+this.u.join(".")+"'"},e}();t.ValidationPath=a},function(e,t,n){"use strict";function r(e){o=e}function i(e){a=e}Object.defineProperty(t,"__esModule",{value:!0});var o,a,s=n(2),u=n(16),l=n(1),h=n(6),c=n(17);t.setNodeFromJSON=r,t.setMaxNode=i;var p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s.__extends(t,e),t.prototype.compare=function(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?l.nameCompare(e.name,t.name):i},t.prototype.isDefinedOn=function(e){return!e.getPriority().isEmpty()},t.prototype.indexedValueChanged=function(e,t){return!e.getPriority().equals(t.getPriority())},t.prototype.minPost=function(){return h.NamedNode.MIN},t.prototype.maxPost=function(){return new h.NamedNode(l.MAX_NAME,new c.LeafNode("[PRIORITY-POST]",a))},t.prototype.makePost=function(e,t){var n=o(e);return new h.NamedNode(t,new c.LeafNode("[PRIORITY-POST]",n))},t.prototype.toString=function(){return".priority"},t}(u.Index);t.PriorityIndex=p,t.PRIORITY_INDEX=new p},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i=n(2),o=n(0),a=n(1),s=n(18),u=n(6),l=n(39),h=n(4),c=n(12),p=n(41),d=n(17),f=n(43),_=function(){function e(e,t,n){this._=e,this.y=t,this.g=n,this.m=null,this.y&&l.validatePriorityNode(this.y),this._.isEmpty()&&o.assert(!this.y||this.y.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(e,"EMPTY_NODE",{get:function(){return r||(r=new e(new s.SortedMap(f.NAME_COMPARATOR),null,p.IndexMap.Default))},enumerable:!0,configurable:!0}),e.prototype.isLeafNode=function(){return!1},e.prototype.getPriority=function(){return this.y||r},e.prototype.updatePriority=function(t){return this._.isEmpty()?this:new e(this._,t,this.g)},e.prototype.getImmediateChild=function(e){if(".priority"===e)return this.getPriority();var t=this._.get(e);return null===t?r:t},e.prototype.getChild=function(e){var t=e.getFront();return null===t?this:this.getImmediateChild(t).getChild(e.popFront())},e.prototype.hasChild=function(e){return null!==this._.get(e)},e.prototype.updateImmediateChild=function(t,n){if(o.assert(n,"We should always be passing snapshot nodes"),".priority"===t)return this.updatePriority(n);var i=new u.NamedNode(t,n),a=void 0,s=void 0,l=void 0;return n.isEmpty()?(a=this._.remove(t),s=this.g.removeFromIndexes(i,this._)):(a=this._.insert(t,n),s=this.g.addToIndexes(i,this._)),l=a.isEmpty()?r:this.y,new e(a,l,s)},e.prototype.updateChild=function(e,t){var n=e.getFront();if(null===n)return t;o.assert(".priority"!==e.getFront()||1===e.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(e.popFront(),t);return this.updateImmediateChild(n,r)},e.prototype.isEmpty=function(){return this._.isEmpty()},e.prototype.numChildren=function(){return this._.count()},e.prototype.val=function(t){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(h.PRIORITY_INDEX,function(a,s){n[a]=s.val(t),r++,o&&e.e.test(a)?i=Math.max(i,+a):o=!1}),!t&&o&&i<2*r){var a=[];for(var s in n)a[s]=n[s];return a}return t&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},e.prototype.hash=function(){if(null===this.m){var e="";this.getPriority().isEmpty()||(e+="priority:"+l.priorityHashText(this.getPriority().val())+":"),this.forEachChild(h.PRIORITY_INDEX,function(t,n){var r=n.hash();""!==r&&(e+=":"+t+":"+r)}),this.m=""===e?"":a.sha1(e)}return this.m},e.prototype.getPredecessorChildName=function(e,t,n){var r=this.C(n);if(r){var i=r.getPredecessorKey(new u.NamedNode(e,t));return i?i.name:null}return this._.getPredecessorKey(e)},e.prototype.getFirstChildName=function(e){var t=this.C(e);if(t){var n=t.minKey();return n&&n.name}return this._.minKey()},e.prototype.getFirstChild=function(e){var t=this.getFirstChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.getLastChildName=function(e){var t=this.C(e);if(t){var n=t.maxKey();return n&&n.name}return this._.maxKey()},e.prototype.getLastChild=function(e){var t=this.getLastChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.forEachChild=function(e,t){var n=this.C(e);return n?n.inorderTraversal(function(e){return t(e.name,e.node)}):this._.inorderTraversal(t)},e.prototype.getIterator=function(e){return this.getIteratorFrom(e.minPost(),e)},e.prototype.getIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getIteratorFrom(e,function(e){return e});for(var r=this._.getIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)<0;)r.getNext(),i=r.peek();return r},e.prototype.getReverseIterator=function(e){return this.getReverseIteratorFrom(e.maxPost(),e)},e.prototype.getReverseIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getReverseIteratorFrom(e,function(e){return e});for(var r=this._.getReverseIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)>0;)r.getNext(),i=r.peek();return r},e.prototype.compareTo=function(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===t.MAX_NODE?-1:0},e.prototype.withIndex=function(t){if(t===c.KEY_INDEX||this.g.hasIndex(t))return this;var n=this.g.addIndex(t,this._);return new e(this._,this.y,n)},e.prototype.isIndexed=function(e){return e===c.KEY_INDEX||this.g.hasIndex(e)},e.prototype.equals=function(e){if(e===this)return!0;if(e.isLeafNode())return!1;var t=e;if(this.getPriority().equals(t.getPriority())){if(this._.count()===t._.count()){for(var n=this.getIterator(h.PRIORITY_INDEX),r=t.getIterator(h.PRIORITY_INDEX),i=n.getNext(),o=r.getNext();i&&o;){if(i.name!==o.name||!i.node.equals(o.node))return!1;i=n.getNext(),o=r.getNext()}return null===i&&null===o}return!1}return!1},e.prototype.C=function(e){return e===c.KEY_INDEX?null:this.g.get(""+e)},e.e=/^(0|[1-9]\d*)$/,e}();t.ChildrenNode=_;var y=function(e){function t(){return e.call(this,new s.SortedMap(f.NAME_COMPARATOR),_.EMPTY_NODE,p.IndexMap.Default)||this}return i.__extends(t,e),t.prototype.compareTo=function(e){return e===this?0:1},t.prototype.equals=function(e){return e===this},t.prototype.getPriority=function(){return this},t.prototype.getImmediateChild=function(e){return _.EMPTY_NODE},t.prototype.isEmpty=function(){return!1},t}(_);t.MaxNode=y,t.MAX_NODE=new y,Object.defineProperties(u.NamedNode,{MIN:{value:new u.NamedNode(a.MIN_NAME,_.EMPTY_NODE)},MAX:{value:new u.NamedNode(a.MAX_NAME,t.MAX_NODE)}}),c.KeyIndex.__EMPTY_NODE=_.EMPTY_NODE,d.LeafNode.__childrenNodeConstructor=_,l.setMaxNode(t.MAX_NODE),h.setMaxNode(t.MAX_NODE)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){this.name=e,this.node=t}return e.Wrap=function(t,n){return new e(t,n)},e}();t.NamedNode=r},,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(3),i=n(0),o=n(1),a=n(0),s=n(0);t.N=/[\[\].#$\/\u0000-\u001F\u007F]/,t.P=/[\[\].#$\u0000-\u001F\u007F]/,t.S=10485760,t.isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!t.N.test(e)},t.isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!t.P.test(e)},t.isValidRootPathString=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),t.isValidPathString(e)},t.isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!o.isInvalidJSONNumber(e)||e&&"object"==typeof e&&i.contains(e,".sv")},t.validateFirebaseDataArg=function(e,n,r,i,o){o&&void 0===r||t.validateFirebaseData(a.errorPrefix(e,n,o),r,i)},t.validateFirebaseData=function(e,n,a){var u=a instanceof r.Path?new r.ValidationPath(a,e):a;if(void 0===n)throw Error(e+"contains undefined "+u.toErrorString());if("function"==typeof n)throw Error(e+"contains a function "+u.toErrorString()+" with contents = "+n);if(o.isInvalidJSONNumber(n))throw Error(e+"contains "+n+" "+u.toErrorString());if("string"==typeof n&&n.length>t.S/3&&s.stringLength(n)>t.S)throw Error(e+"contains a string greater than "+t.S+" utf8 bytes "+u.toErrorString()+" ('"+n.substring(0,50)+"...')");if(n&&"object"==typeof n){var l=!1,h=!1;if(i.forEach(n,function(n,r){if(".value"===n)l=!0;else if(".priority"!==n&&".sv"!==n&&(h=!0,!t.isValidKey(n)))throw Error(e+" contains an invalid key ("+n+") "+u.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');u.push(n),t.validateFirebaseData(e,r,u),u.pop()}),l&&h)throw Error(e+' contains ".value" child '+u.toErrorString()+" in addition to actual children.")}},t.validateFirebaseMergePaths=function(e,n){var i,o;for(i=0;i=0,"Unknown leaf type: "+n),i.assert(a>=0,"Unknown leaf type: "+r),o===a?"object"===r?0:this.T0},e.prototype.peek=function(){if(0===this.O.length)return null;var e=this.O[this.O.length-1];return this.w?this.w(e.key,e.value):{key:e.key,value:e.value}},e}();t.SortedMapIterator=r;var i=function(){function e(t,n,r,i,o){this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:a.EMPTY_NODE,this.right=null!=o?o:a.EMPTY_NODE}return e.prototype.copy=function(t,n,r,i,o){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},e.prototype.count=function(){return this.left.count()+1+this.right.count()},e.prototype.isEmpty=function(){return!1},e.prototype.inorderTraversal=function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)},e.prototype.A=function(){return this.left.isEmpty()?this:this.left.A()},e.prototype.minKey=function(){return this.A().key},e.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},e.prototype.insert=function(e,t,n){var r,i;return i=this,r=n(e,i.key),i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.D()},e.prototype.M=function(){if(this.left.isEmpty())return a.EMPTY_NODE;var e=this;return e.left.L()||e.left.left.L()||(e=e.F()),e=e.copy(null,null,null,e.left.M(),null),e.D()},e.prototype.remove=function(e,t){var n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.L()||n.left.left.L()||(n=n.F()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.L()&&(n=n.x()),n.right.isEmpty()||n.right.L()||n.right.left.L()||(n=n.k()),0===t(e,n.key)){if(n.right.isEmpty())return a.EMPTY_NODE;r=n.right.A(),n=n.copy(r.key,r.value,null,null,n.right.M())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.D()},e.prototype.L=function(){return this.color},e.prototype.D=function(){var e=this;return e.right.L()&&!e.left.L()&&(e=e.W()),e.left.L()&&e.left.left.L()&&(e=e.x()),e.left.L()&&e.right.L()&&(e=e.V()),e},e.prototype.F=function(){var e=this.V();return e.right.left.L()&&(e=e.copy(null,null,null,null,e.right.x()),e=e.W(),e=e.V()),e},e.prototype.k=function(){var e=this.V();return e.left.left.L()&&(e=e.x(),e=e.V()),e},e.prototype.W=function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)},e.prototype.x=function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)},e.prototype.V=function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)},e.prototype.Q=function(){var e=this.j();return Math.pow(2,e)<=this.count()+1},e.prototype.j=function(){var e;if(this.L()&&this.left.L())throw Error("Red node has red child("+this.key+","+this.value+")");if(this.right.L())throw Error("Right child of ("+this.key+","+this.value+") is red");if((e=this.left.j())!==this.right.j())throw Error("Black depths differ");return e+(this.L()?0:1)},e.RED=!0,e.BLACK=!1,e}();t.LLRBNode=i;var o=function(){function e(){}return e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new i(e,t,null)},e.prototype.remove=function(e,t){return this},e.prototype.count=function(){return 0},e.prototype.isEmpty=function(){return!0},e.prototype.inorderTraversal=function(e){return!1},e.prototype.reverseTraversal=function(e){return!1},e.prototype.minKey=function(){return null},e.prototype.maxKey=function(){return null},e.prototype.j=function(){return 0},e.prototype.L=function(){return!1},e}();t.LLRBEmptyNode=o;var a=function(){function e(t,n){void 0===n&&(n=e.EMPTY_NODE),this.U=t,this.B=n}return e.prototype.insert=function(t,n){return new e(this.U,this.B.insert(t,n,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.remove=function(t){return new e(this.U,this.B.remove(t,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.get=function(e){for(var t,n=this.B;!n.isEmpty();){if(0===(t=this.U(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null},e.prototype.getPredecessorKey=function(e){for(var t,n=this.B,r=null;!n.isEmpty();){if(0===(t=this.U(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw Error("Attempted to find predecessor key for a nonexistent key. What gives?")},e.prototype.isEmpty=function(){return this.B.isEmpty()},e.prototype.count=function(){return this.B.count()},e.prototype.minKey=function(){return this.B.minKey()},e.prototype.maxKey=function(){return this.B.maxKey()},e.prototype.inorderTraversal=function(e){return this.B.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.B.reverseTraversal(e)},e.prototype.getIterator=function(e){return new r(this.B,null,this.U,!1,e)},e.prototype.getIteratorFrom=function(e,t){return new r(this.B,e,this.U,!1,t)},e.prototype.getReverseIteratorFrom=function(e,t){return new r(this.B,e,this.U,!0,t)},e.prototype.getReverseIterator=function(e){return new r(this.B,null,this.U,!0,e)},e.EMPTY_NODE=new o,e}();t.SortedMap=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(45),i=n(13),o=n(3),a=n(46),s=n(88),u=n(99),l=n(0),h=n(1),c=n(0),p=n(100),d=n(27),f=n(102),_=n(51),y=n(103),v=n(52),g=n(108),m=n(34),C=function(){function e(e,t,n){var r=this;this.H=e,this.app=n,this.dataUpdateCount=0,this.G=null,this.K=new y.EventQueue,this.Y=1,this.X=null,this.z=new a.SparseSnapshotTree,this.J=null;var i=new p.AuthTokenProvider(n);if(this.$=d.StatsManager.getCollection(e),t||h.beingCrawled())this.Z=new g.ReadonlyRestClient(this.H,this.ee.bind(this),i),setTimeout(this.te.bind(this,!0),0);else{var o=n.options.databaseAuthVariableOverride;if(void 0!==o&&null!==o){if("object"!=typeof o)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{l.stringify(o)}catch(e){throw Error("Invalid authOverride provided: "+e)}}this.J=new v.PersistentConnection(this.H,this.ee.bind(this),this.te.bind(this),this.ne.bind(this),i,o),this.Z=this.J}i.addTokenChangeListener(function(e){r.Z.refreshAuthToken(e)}),this.re=d.StatsManager.getOrCreateReporter(e,function(){return new f.StatsReporter(r.$,r.Z)}),this.ie(),this.oe=new u.SnapshotHolder,this.ae=new s.SyncTree({startListening:function(e,t,n,i){var o=[],a=r.oe.getNode(e.path);return a.isEmpty()||(o=r.ae.applyServerOverwrite(e.path,a),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.se("connected",!1),this.ue=new s.SyncTree({startListening:function(e,t,n,i){return r.Z.listen(e,n,t,function(t,n){var o=i(t,n);r.K.raiseEventsForChangedPath(e.path,o)}),[]},stopListening:function(e,t){r.Z.unlisten(e,t)}})}return e.prototype.toString=function(){return(this.H.secure?"https://":"http://")+this.H.host},e.prototype.name=function(){return this.H.namespace},e.prototype.serverTime=function(){var e=this.oe.getNode(new o.Path(".info/serverTimeOffset")),t=e.val()||0;return(new Date).getTime()+t},e.prototype.generateServerValues=function(){return r.generateWithValues({timestamp:this.serverTime()})},e.prototype.ee=function(e,t,n,r){this.dataUpdateCount++;var a=new o.Path(e);t=this.X?this.X(e,t):t;var s=[];if(r)if(n){var u=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyTaggedQueryMerge(a,u,r)}else{var l=i.nodeFromJSON(t);s=this.ue.applyTaggedQueryOverwrite(a,l,r)}else if(n){var h=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyServerMerge(a,h)}else{var p=i.nodeFromJSON(t);s=this.ue.applyServerOverwrite(a,p)}var d=a;s.length>0&&(d=this.le(a)),this.K.raiseEventsForChangedPath(d,s)},e.prototype.he=function(e){this.X=e},e.prototype.te=function(e){this.se("connected",e),!1===e&&this.ce()},e.prototype.ne=function(e){var t=this;h.each(e,function(e,n){t.se(n,e)})},e.prototype.se=function(e,t){var n=new o.Path("/.info/"+e),r=i.nodeFromJSON(t);this.oe.updateSnapshot(n,r);var a=this.ae.applyServerOverwrite(n,r);this.K.raiseEventsForChangedPath(n,a)},e.prototype.pe=function(){return this.Y++},e.prototype.setWithPriority=function(e,t,n,o){var a=this;this.de("set",{path:""+e,value:t,priority:n});var s=this.generateServerValues(),u=i.nodeFromJSON(t,n),l=r.resolveDeferredValueSnapshot(u,s),c=this.pe(),p=this.ue.applyUserOverwrite(e,l,c,!0);this.K.queueEvents(p),this.Z.put(""+e,u.val(!0),function(t,n){var r="ok"===t;r||h.warn("set at "+e+" failed: "+t);var i=a.ue.ackUserWrite(c,!r);a.K.raiseEventsForChangedPath(e,i),a.callOnCompleteCallback(o,t,n)});var d=this.fe(e);this.le(d),this.K.raiseEventsForChangedPath(d,[])},e.prototype.update=function(e,t,n){var o=this;this.de("update",{path:""+e,value:t});var a=!0,s=this.generateServerValues(),u={};if(c.forEach(t,function(e,t){a=!1;var n=i.nodeFromJSON(t);u[e]=r.resolveDeferredValueSnapshot(n,s)}),a)h.log("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var l=this.pe(),p=this.ue.applyUserMerge(e,u,l);this.K.queueEvents(p),this.Z.merge(""+e,t,function(t,r){var i="ok"===t;i||h.warn("update at "+e+" failed: "+t);var a=o.ue.ackUserWrite(l,!i),s=a.length>0?o.le(e):e;o.K.raiseEventsForChangedPath(s,a),o.callOnCompleteCallback(n,t,r)}),c.forEach(t,function(t){var n=o.fe(e.child(t));o.le(n)}),this.K.raiseEventsForChangedPath(e,[])}},e.prototype.ce=function(){var e=this;this.de("onDisconnectEvents");var t=this.generateServerValues(),n=r.resolveDeferredValueTree(this.z,t),i=[];n.forEachTree(o.Path.Empty,function(t,n){i=i.concat(e.ue.applyServerOverwrite(t,n));var r=e.fe(t);e.le(r)}),this.z=new a.SparseSnapshotTree,this.K.raiseEventsForChangedPath(o.Path.Empty,i)},e.prototype.onDisconnectCancel=function(e,t){var n=this;this.Z.onDisconnectCancel(""+e,function(r,i){"ok"===r&&n.z.forget(e),n.callOnCompleteCallback(t,r,i)})},e.prototype.onDisconnectSet=function(e,t,n){var r=this,o=i.nodeFromJSON(t);this.Z.onDisconnectPut(""+e,o.val(!0),function(t,i){"ok"===t&&r.z.remember(e,o),r.callOnCompleteCallback(n,t,i)})},e.prototype.onDisconnectSetWithPriority=function(e,t,n,r){var o=this,a=i.nodeFromJSON(t,n);this.Z.onDisconnectPut(""+e,a.val(!0),function(t,n){"ok"===t&&o.z.remember(e,a),o.callOnCompleteCallback(r,t,n)})},e.prototype.onDisconnectUpdate=function(e,t,n){var r=this;if(c.isEmpty(t))return h.log("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.Z.onDisconnectMerge(""+e,t,function(o,a){"ok"===o&&c.forEach(t,function(t,n){var o=i.nodeFromJSON(n);r.z.remember(e.child(t),o)}),r.callOnCompleteCallback(n,o,a)})},e.prototype.addEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.addEventRegistration(e,t):this.ue.addEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.removeEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.removeEventRegistration(e,t):this.ue.removeEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.interrupt=function(){this.J&&this.J.interrupt("repo_interrupt")},e.prototype.resume=function(){this.J&&this.J.resume("repo_interrupt")},e.prototype.stats=function(e){if(void 0===e&&(e=!1),"undefined"!=typeof console){var t;e?(this.G||(this.G=new _.StatsListener(this.$)),t=this.G.get()):t=this.$.get();var n=Object.keys(t).reduce(function(e,t){return Math.max(t.length,e)},0);c.forEach(t,function(e,t){for(var r=e.length;r0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}function i(e){var t={};e.startsWith("?")&&(e=e.substring(1));for(var n=0,r=e.split("&");n.firebaseio.com instead"),r&&"undefined"!=r||"localhost"===n.domain||s.fatal("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||s.warnIfPageIsSecure();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new a.RepoInfo(n.host,n.secure,r,i),path:new o.Path(n.pathString)}},t.parseURL=function(e){var t="",n="",o="",a="",s=!0,u="https",l=443;if("string"==typeof e){var h=e.indexOf("//");h>=0&&(u=e.substring(0,h-1),e=e.substring(h+2));var c=e.indexOf("/");-1===c&&(c=e.length);var p=e.indexOf("?");-1===p&&(p=e.length),t=e.substring(0,Math.min(c,p)),c=0?(s="https"===u||"wss"===u,l=parseInt(t.substring(h+1),10)):h=e.length;var f=t.split(".");3===f.length?(n=f[1],o=f[0].toLowerCase()):2===f.length?n=f[0]:"localhost"===f[0].slice(0,h).toLowerCase()&&(n="localhost"),""===o&&"ns"in d&&(o=d.ns)}return{host:t,port:l,domain:n,subdomain:o,secure:s,scheme:u,pathString:a}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(14),a=n(15),s=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this.secure=t,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=e.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=o.PersistentStorage.get("host:"+e)||this.host}return e.prototype.needsQueryParam=function(){return this.host!==this.internalHost||this.isCustomHost()},e.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},e.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},e.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},e.prototype.updateHost=function(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&o.PersistentStorage.set("host:"+this.host,this.internalHost))},e.prototype.connectionURL=function(e,t){r.assert("string"==typeof e,"typeof type must == string"),r.assert("object"==typeof t,"typeof params must == object");var n;if(e===a.WEBSOCKET)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(e!==a.LONG_POLLING)throw Error("Unknown connection type: "+e);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(t.ns=this.namespace);var o=[];return i.forEach(t,function(e,t){o.push(e+"="+t)}),n+o.join("&")},e.prototype.toString=function(){var e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e},e.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},e}();t.RepoInfo=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(8),o=n(1),a=n(0),s=function(){function e(e,t){this.Oe=e,this.De=t}return e.prototype.cancel=function(e){r.validateArgCount("OnDisconnect.cancel",0,1,arguments.length),r.validateCallback("OnDisconnect.cancel",1,e,!0);var t=new a.Deferred;return this.Oe.onDisconnectCancel(this.De,t.wrapCallback(e)),t.promise},e.prototype.remove=function(e){r.validateArgCount("OnDisconnect.remove",0,1,arguments.length),i.validateWritablePath("OnDisconnect.remove",this.De),r.validateCallback("OnDisconnect.remove",1,e,!0);var t=new a.Deferred;return this.Oe.onDisconnectSet(this.De,null,t.wrapCallback(e)),t.promise},e.prototype.set=function(e,t){r.validateArgCount("OnDisconnect.set",1,2,arguments.length),i.validateWritablePath("OnDisconnect.set",this.De),i.validateFirebaseDataArg("OnDisconnect.set",1,e,this.De,!1),r.validateCallback("OnDisconnect.set",2,t,!0);var n=new a.Deferred;return this.Oe.onDisconnectSet(this.De,e,n.wrapCallback(t)),n.promise},e.prototype.setWithPriority=function(e,t,n){r.validateArgCount("OnDisconnect.setWithPriority",2,3,arguments.length),i.validateWritablePath("OnDisconnect.setWithPriority",this.De),i.validateFirebaseDataArg("OnDisconnect.setWithPriority",1,e,this.De,!1),i.validatePriority("OnDisconnect.setWithPriority",2,t,!1),r.validateCallback("OnDisconnect.setWithPriority",3,n,!0);var o=new a.Deferred;return this.Oe.onDisconnectSetWithPriority(this.De,e,t,o.wrapCallback(n)),o.promise},e.prototype.update=function(e,t){if(r.validateArgCount("OnDisconnect.update",1,2,arguments.length),i.validateWritablePath("OnDisconnect.update",this.De),Array.isArray(e)){for(var n={},s=0;s3e4&&(this.it=v),this.vt=null}}else this.de("Window isn't visible. Delaying reconnect."),this.it=this.ot,this.yt=(new Date).getTime();var t=(new Date).getTime()-this.yt,n=Math.max(0,this.it-t);n=Math.random()*n,this.de("Trying to reconnect in "+n+"ms"),this.gt(n),this.it=Math.min(this.ot,1.3*this.it)}this.te(!1)},t.prototype.kt=function(){if(this.Qt()){this.de("Making a connection attempt"),this.yt=(new Date).getTime(),this.vt=null;var e=this.wt.bind(this),n=this.Mt.bind(this),r=this.Wt.bind(this),i=this.id+":"+t.qt++,o=this,a=this.lastSessionId,l=!1,h=null,c=function(){h?h.close():(l=!0,r())},p=function(e){s.assert(h,"sendRequest call when we're not connected not allowed."),h.sendRequest(e)};this.ct={close:c,sendRequest:p};var _=this.dt;this.dt=!1,this.Xe.getToken(_).then(function(t){l?u.log("getToken() completed but was canceled"):(u.log("getToken() completed. Creating connection."),o.pt=t&&t.accessToken,h=new d.Connection(i,o.H,e,n,r,function(e){u.warn(e+" ("+o.H+")"),o.interrupt("server_kill")},a))}).then(null,function(e){o.de("Failed to get token: "+e),l||(f.CONSTANTS.NODE_ADMIN&&u.warn(e),c())})}},t.prototype.interrupt=function(e){u.log("Interrupting connection for reason: "+e),this.$e[e]=!0,this.ct?this.ct.close():(this.st&&(clearTimeout(this.st),this.st=null),this.rt&&this.Wt())},t.prototype.resume=function(e){u.log("Resuming connection for reason: "+e),delete this.$e[e],o.isEmpty(this.$e)&&(this.it=v,this.ct||this.gt(0))},t.prototype.Lt=function(e){var t=e-(new Date).getTime();this.ne({serverTimeOffset:t})},t.prototype.Vt=function(){for(var e=0;e=3&&(this.it=3e4,this.Xe.notifyForInvalidToken())},t.prototype.Dt=function(e){this.at?this.at(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))},t.prototype.xt=function(){var e=this;this.tryAuth(),o.forEach(this.Ze,function(t,n){o.forEach(n,function(t,n){e.Et(n)})});for(var t=0;t0,"Requires a non-empty array")}return e.prototype.trigger=function(e){for(var t=[],n=1;n0&&(this.an=r.setTimeoutNonBlocking(function(){e.an=null,e.in||(e.zt&&e.zt.bytesReceived>102400?(e.de("Connection exceeded healthy timeout but has received "+e.zt.bytesReceived+" bytes. Marking connection healthy."),e.in=!0,e.zt.markConnectionHealthy()):e.zt&&e.zt.bytesSent>10240?e.de("Connection exceeded healthy timeout but has sent "+e.zt.bytesSent+" bytes. Leaving connection alive."):(e.de("Closing unhealthy connection after timeout."),e.close()))},Math.floor(o)))},e.prototype.Jt=function(){return"c:"+this.id+":"+this.connectionCount++},e.prototype.en=function(e){var t=this;return function(n){e===t.zt?t.sn(n):e===t.rn?(t.de("Secondary connection lost."),t.un()):t.de("closing an old connection")}},e.prototype.Zt=function(e){var t=this;return function(n){2!=t.Kt&&(e===t.nn?t.ln(n):e===t.rn?t.hn(n):t.de("message on old connection"))}},e.prototype.sendRequest=function(e){var t={t:"d",d:e};this.cn(t)},e.prototype.tryCleanupConnection=function(){this.tn===this.rn&&this.nn===this.rn&&(this.de("cleaning up and promoting a connection: "+this.rn.connId),this.zt=this.rn,this.rn=null)},e.prototype.pn=function(e){if("t"in e){var t=e.t;"a"===t?this.dn():"r"===t?(this.de("Got a reset on secondary, closing it"),this.rn.close(),this.tn!==this.rn&&this.nn!==this.rn||this.close()):"o"===t&&(this.de("got pong on secondary."),this.fn--,this.dn())}},e.prototype.hn=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);if("c"==t)this.pn(n);else{if("d"!=t)throw Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}},e.prototype.dn=function(){this.fn<=0?(this.de("Secondary connection is healthy."),this.in=!0,this.rn.markConnectionHealthy(),this._n()):(this.de("sending ping on secondary."),this.rn.send({t:"c",d:{t:"p",d:{}}}))},e.prototype._n=function(){this.rn.start(),this.de("sending client ack on secondary"),this.rn.send({t:"c",d:{t:"a",d:{}}}),this.de("Ending transmission on primary"),this.zt.send({t:"c",d:{t:"n",d:{}}}),this.tn=this.rn,this.tryCleanupConnection()},e.prototype.ln=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);"c"==t?this.yn(n):"d"==t&&this.wt(n)},e.prototype.wt=function(e){this.vn(),this.Ht(e)},e.prototype.vn=function(){this.in||--this.$t<=0&&(this.de("Primary connection is healthy."),this.in=!0,this.zt.markConnectionHealthy())},e.prototype.yn=function(e){var t=r.requireKey("t",e);if("d"in e){var n=e.d;if("h"===t)this.gn(n);else if("n"===t){this.de("recvd end transmission on primary"),this.nn=this.rn;for(var i=0;idocument.domain="'+document.domain+'";<\/script>');var h=""+u+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(h),this.myIFrame.doc.close()}catch(e){r.log("frame writing exception"),e.stack&&r.log(e.stack),r.log(e)}}}return e.Ln=function(){var e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||r.log("No IE domain setting required")}catch(n){var t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e},e.prototype.close=function(){var n=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==n.myIFrame&&(document.body.removeChild(n.myIFrame),n.myIFrame=null)},Math.floor(0))),l.isNodeSdk()&&this.myID){var r={};r[t.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM]="t",r[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,r[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW;var i=this.urlFn(r);e.nodeRestRequest(i)}var o=this.onDisconnect;o&&(this.onDisconnect=null,o())},e.prototype.startLongPoll=function(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.Fn(););},e.prototype.Fn=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var e={};e[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,e[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW,e[t.FIREBASE_LONGPOLL_SERIAL_PARAM]=this.currentSerial;for(var n=this.urlFn(e),r="",i=0;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+r.length<=1870;){var o=this.pendingSegs.shift();r=r+"&"+t.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM+i+"="+o.seg+"&"+t.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET+i+"="+o.ts+"&"+t.FIREBASE_LONGPOLL_DATA_PARAM+i+"="+o.d,i++}return n+=r,this.xn(n,this.currentSerial),!0}return!1},e.prototype.enqueueSegment=function(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.Fn()},e.prototype.xn=function(e,t){var n=this;this.outstandingRequests.add(t,1);var r=function(){n.outstandingRequests.remove(t),n.Fn()},i=setTimeout(r,Math.floor(25e3)),o=function(){clearTimeout(i),r()};this.addTag(e,o)},e.prototype.addTag=function(e,t){var n=this;l.isNodeSdk()?this.doNodeLongPoll(e,t):setTimeout(function(){try{if(!n.sendNewPolls)return;var i=n.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){var e=i.readyState;e&&"loaded"!==e&&"complete"!==e||(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=function(){r.log("Long-poll script failed to load: "+e),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(i)}catch(e){}},Math.floor(1))},e}();t.FirebaseIFrameScriptHolder=c},function(e,t,n){"use strict";(function(e){function r(e){d=e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(7),o=n(0),a=n(1),s=n(27),u=n(15),l=n(0),h=n(14),c=n(0),p=n(0),d=null;"undefined"!=typeof MozWebSocket?d=MozWebSocket:"undefined"!=typeof WebSocket&&(d=WebSocket),t.setWebSocketImpl=r;var f=function(){function t(e,n,r,i){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.de=a.logWrapper(this.connId),this.$=s.StatsManager.getCollection(n),this.connURL=t.kn(n,r,i)}return t.kn=function(e,t,n){var r={};return r[u.VERSION_PARAM]=u.PROTOCOL_VERSION,!p.isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf(u.FORGE_DOMAIN)&&(r[u.REFERER_PARAM]=u.FORGE_REF),t&&(r[u.TRANSPORT_SESSION_PARAM]=t),n&&(r[u.LAST_SESSION_PARAM]=n),e.connectionURL(u.WEBSOCKET,r)},t.prototype.open=function(t,n){var r=this;this.onDisconnect=n,this.onMessage=t,this.de("Websocket connecting to "+this.connURL),this.Tn=!1,h.PersistentStorage.set("previous_websocket_failure",!0);try{if(p.isNodeSdk()){var o=l.CONSTANTS.NODE_ADMIN?"AdminNode":"Node",a={headers:{"User-Agent":"Firebase/"+u.PROTOCOL_VERSION+"/"+i.default.SDK_VERSION+"/"+e.platform+"/"+o}},s=e.env,c=0==this.connURL.indexOf("wss://")?s.HTTPS_PROXY||s.https_proxy:s.HTTP_PROXY||s.http_proxy;c&&(a.proxy={origin:c}),this.mySock=new d(this.connURL,[],a)}else this.mySock=new d(this.connURL)}catch(e){this.de("Error instantiating WebSocket.");var f=e.message||e.data;return f&&this.de(f),void this.wn()}this.mySock.onopen=function(){r.de("Websocket connected."),r.Tn=!0},this.mySock.onclose=function(){r.de("Websocket connection was disconnected."),r.mySock=null,r.wn()},this.mySock.onmessage=function(e){r.handleIncomingFrame(e)},this.mySock.onerror=function(e){r.de("WebSocket error. Closing connection.");var t=e.message||e.data;t&&r.de(t),r.wn()}},t.prototype.start=function(){},t.forceDisallow=function(){t.Dn=!0},t.isAvailable=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=/Android ([0-9]{0,}\.[0-9]{0,})/,r=navigator.userAgent.match(n);r&&r.length>1&&parseFloat(r[1])<4.4&&(e=!0)}return!e&&null!==d&&!t.Dn},t.previouslyFailed=function(){return h.PersistentStorage.isInMemoryStorage||!0===h.PersistentStorage.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){h.PersistentStorage.remove("previous_websocket_failure")},t.prototype.Wn=function(e){if(this.frames.push(e),this.frames.length==this.totalFrames){var t=this.frames.join("");this.frames=null;var n=c.jsonEval(t);this.onMessage(n)}},t.prototype.Vn=function(e){this.totalFrames=e,this.frames=[]},t.prototype.Qn=function(e){if(o.assert(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=+e;if(!isNaN(t))return this.Vn(t),null}return this.Vn(1),e},t.prototype.handleIncomingFrame=function(e){if(null!==this.mySock){var t=e.data;if(this.bytesReceived+=t.length,this.$.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.Wn(t);else{var n=this.Qn(t);null!==n&&this.Wn(n)}}},t.prototype.send=function(e){this.resetKeepAlive();var t=c.stringify(e);this.bytesSent+=t.length,this.$.incrementCounter("bytes_sent",t.length);var n=a.splitStringBySize(t,16384);n.length>1&&this.qn(n.length+"");for(var r=0;r=0;a--)s[a]=e.charAt(i%64),i=Math.floor(i/64);r.assert(0===i,"Cannot push at time == 0");var u=s.join("");if(o){for(a=11;a>=0&&63===n[a];a--)n[a]=0;n[a]++}else for(a=0;a<12;a++)n[a]=Math.floor(64*Math.random());for(a=0;a<12;a++)u+=e.charAt(n[a]);return r.assert(20===u.length,"nextPushId: Length should be 20."),u}}()},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(24),i=n(87),o=n(0),a=n(0),s=function(){function e(e,t,n){this.Jn=e,this.$n=t,this.Zn=n}return e.prototype.respondsTo=function(e){return"value"===e},e.prototype.createEvent=function(e,t){var n=t.getQueryParams().getIndex();return new i.DataEvent("value",this,new r.DataSnapshot(e.snapshotNode,t.getRef(),n))},e.prototype.getEventRunner=function(e){var t=this.Zn;if("cancel"===e.getEventType()){a.assert(this.$n,"Raising a cancel event on a listener with no cancel callback");var n=this.$n;return function(){n.call(t,e.error)}}var r=this.Jn;return function(){r.call(t,e.snapshot)}},e.prototype.createCancelEvent=function(e,t){return this.$n?new i.CancelEvent(this,e,t):null},e.prototype.matches=function(t){return t instanceof e&&(!t.Jn||!this.Jn||t.Jn===this.Jn&&t.Zn===this.Zn)},e.prototype.hasAnyCallback=function(){return null!==this.Jn},e}();t.ValueEventRegistration=s;var u=function(){function e(e,t,n){this.er=e,this.$n=t,this.Zn=n}return e.prototype.respondsTo=function(e){var t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,o.contains(this.er,t)},e.prototype.createCancelEvent=function(e,t){return this.$n?new i.CancelEvent(this,e,t):null},e.prototype.createEvent=function(e,t){a.assert(null!=e.childName,"Child events should have a childName.");var n=t.getRef().child(e.childName),o=t.getQueryParams().getIndex();return new i.DataEvent(e.type,this,new r.DataSnapshot(e.snapshotNode,n,o),e.prevName)},e.prototype.getEventRunner=function(e){var t=this.Zn;if("cancel"===e.getEventType()){a.assert(this.$n,"Raising a cancel event on a listener with no cancel callback");var n=this.$n;return function(){n.call(t,e.error)}}var r=this.er[e.eventType];return function(){r.call(t,e.snapshot,e.prevName)}},e.prototype.matches=function(t){if(t instanceof e){if(!this.er||!t.er)return!0;if(this.Zn===t.Zn){var n=o.getCount(t.er);if(n===o.getCount(this.er)){if(1===n){var r=o.getAnyKey(t.er),i=o.getAnyKey(this.er);return!(i!==r||t.er[r]&&this.er[i]&&t.er[r]!==this.er[i])}return o.every(this.er,function(e,n){return t.er[e]===n})}}}return!1},e.prototype.hasAnyCallback=function(){return null!==this.er},e}();t.ChildEventRegistration=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=function(){function e(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}return e.prototype.getPath=function(){var e=this.snapshot.getRef();return"value"===this.eventType?e.path:e.getParent().path},e.prototype.getEventType=function(){return this.eventType},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.getPath()+":"+this.eventType+":"+r.stringify(this.snapshot.exportVal())},e}();t.DataEvent=i;var o=function(){function e(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}return e.prototype.getPath=function(){return this.path},e.prototype.getEventType=function(){return"cancel"},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.path+":cancel"},e}();t.CancelEvent=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(89),a=n(5),s=n(0),u=n(25),l=n(90),h=n(91),c=n(9),p=n(48),d=n(3),f=n(49),_=n(97),y=function(){function e(e){this.tr=e,this.nr=u.ImmutableTree.Empty,this.rr=new _.WriteTree,this.ir={},this.or={}}return e.prototype.applyUserOverwrite=function(e,t,n,r){return this.rr.addOverwrite(e,t,n,r),r?this.ar(new p.Overwrite(c.OperationSource.User,e,t)):[]},e.prototype.applyUserMerge=function(e,t,n){this.rr.addMerge(e,t,n);var r=u.ImmutableTree.fromObject(t);return this.ar(new h.Merge(c.OperationSource.User,e,r))},e.prototype.ackUserWrite=function(e,t){void 0===t&&(t=!1);var n=this.rr.getWrite(e);if(this.rr.removeWrite(e)){var r=u.ImmutableTree.Empty;return null!=n.snap?r=r.set(d.Path.Empty,!0):s.forEach(n.children,function(e,t){r=r.set(new d.Path(e),t)}),this.ar(new o.AckUserWrite(n.path,r,t))}return[]},e.prototype.applyServerOverwrite=function(e,t){return this.ar(new p.Overwrite(c.OperationSource.Server,e,t))},e.prototype.applyServerMerge=function(e,t){var n=u.ImmutableTree.fromObject(t);return this.ar(new h.Merge(c.OperationSource.Server,e,n))},e.prototype.applyListenComplete=function(e){return this.ar(new l.ListenComplete(c.OperationSource.Server,e))},e.prototype.applyTaggedQueryOverwrite=function(t,n,r){var i=this.sr(r);if(null!=i){var o=e.ur(i),a=o.path,s=o.queryId,u=d.Path.relativePath(a,t),l=new p.Overwrite(c.OperationSource.forServerTaggedQuery(s),u,n);return this.lr(a,l)}return[]},e.prototype.applyTaggedQueryMerge=function(t,n,r){var i=this.sr(r);if(i){var o=e.ur(i),a=o.path,s=o.queryId,l=d.Path.relativePath(a,t),p=u.ImmutableTree.fromObject(n),f=new h.Merge(c.OperationSource.forServerTaggedQuery(s),l,p);return this.lr(a,f)}return[]},e.prototype.applyTaggedListenComplete=function(t,n){var r=this.sr(n);if(r){var i=e.ur(r),o=i.path,a=i.queryId,s=d.Path.relativePath(o,t),u=new l.ListenComplete(c.OperationSource.forServerTaggedQuery(a),s);return this.lr(o,u)}return[]},e.prototype.addEventRegistration=function(t,n){var i=t.path,o=null,s=!1;this.nr.foreachOnPath(i,function(e,t){var n=d.Path.relativePath(e,i);o=o||t.getCompleteServerCache(n),s=s||t.hasCompleteView()});var u=this.nr.get(i);u?(s=s||u.hasCompleteView(),o=o||u.getCompleteServerCache(d.Path.Empty)):(u=new f.SyncPoint,this.nr=this.nr.set(i,u));var l;null!=o?l=!0:(l=!1,o=a.ChildrenNode.EMPTY_NODE,this.nr.subtree(i).foreachChild(function(e,t){var n=t.getCompleteServerCache(d.Path.Empty);n&&(o=o.updateImmediateChild(e,n))}));var h=u.viewExistsForQuery(t);if(!h&&!t.getQueryParams().loadsAllData()){var c=e.hr(t);r.assert(!(c in this.or),"View does not exist, but we have a tag");var p=e.cr();this.or[c]=p,this.ir["_"+p]=c}var _=this.rr.childWrites(i),y=u.addEventRegistration(t,n,_,o,l);if(!h&&!s){var v=u.viewForQuery(t);y=y.concat(this.pr(t,v))}return y},e.prototype.removeEventRegistration=function(t,n,r){var i=this,o=t.path,a=this.nr.get(o),s=[];if(a&&("default"===t.queryIdentifier()||a.viewExistsForQuery(t))){var u=a.removeEventRegistration(t,n,r);a.isEmpty()&&(this.nr=this.nr.remove(o));var l=u.removed;s=u.events;var h=-1!==l.findIndex(function(e){return e.getQueryParams().loadsAllData()}),c=this.nr.findOnPath(o,function(e,t){return t.hasCompleteView()});if(h&&!c){var p=this.nr.subtree(o);if(!p.isEmpty())for(var d=this.dr(p),f=0;f0&&!r&&(h?this.tr.stopListening(e._r(t),null):l.forEach(function(t){var n=i.or[e.hr(t)];i.tr.stopListening(e._r(t),n)})),this.vr(l)}return s},e.prototype.calcCompleteEventCache=function(e,t){var n=this.rr,r=this.nr.findOnPath(e,function(t,n){var r=d.Path.relativePath(t,e),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(e,r,t,!0)},e.prototype.dr=function(e){return e.fold(function(e,t,n){if(t&&t.hasCompleteView())return[t.getCompleteView()];var r=[];return t&&(r=t.getQueryViews()),s.forEach(n,function(e,t){r=r.concat(t)}),r})},e.prototype.vr=function(t){for(var n=0;n0||!e.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(a.Change.valueChange(t.getCompleteEventSnap()))}},e.prototype.xr=function(e,t,n,r,o){var a=e.getEventCache();if(null!=n.shadowingWrite(t))return e;var u=void 0,l=void 0;if(t.isEmpty())if(i.assert(e.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),e.getServerCache().isFiltered()){var h=e.getCompleteServerSnap(),c=h instanceof s.ChildrenNode?h:s.ChildrenNode.EMPTY_NODE,p=n.calcCompleteEventChildren(c);u=this.Rr.updateFullNode(e.getEventCache().getNode(),p,o)}else{var d=n.calcCompleteEventCache(e.getCompleteServerSnap());u=this.Rr.updateFullNode(e.getEventCache().getNode(),d,o)}else{var f=t.getFront();if(".priority"==f){i.assert(1==t.getLength(),"Can't have a priority with additional path components");var _=a.getNode();l=e.getServerCache().getNode();var y=n.calcEventCacheAfterServerOverwrite(t,_,l);u=null!=y?this.Rr.updatePriority(_,y):a.getNode()}else{var v=t.popFront(),g=void 0;if(a.isCompleteForChild(f)){l=e.getServerCache().getNode();var m=n.calcEventCacheAfterServerOverwrite(t,a.getNode(),l);g=null!=m?a.getNode().getImmediateChild(f).updateChild(v,m):a.getNode().getImmediateChild(f)}else g=n.calcCompleteChild(f,e.getServerCache());u=null!=g?this.Rr.updateChild(a.getNode(),f,g,v,r,o):a.getNode()}}return e.updateEventSnap(u,a.isFullyInitialized()||t.isEmpty(),this.Rr.filtersNodes())},e.prototype.wr=function(e,t,n,r,i,o,a){var s,u=e.getServerCache(),l=o?this.Rr:this.Rr.getIndexedFilter();if(t.isEmpty())s=l.updateFullNode(u.getNode(),n,null);else if(l.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(t,n);s=l.updateFullNode(u.getNode(),h,null)}else{var p=t.getFront();if(!u.isCompleteForPath(t)&&t.getLength()>1)return e;var d=t.popFront(),f=u.getNode().getImmediateChild(p),_=f.updateChild(d,n);s=".priority"==p?l.updatePriority(u.getNode(),_):l.updateChild(u.getNode(),p,_,d,c.NO_COMPLETE_CHILD_SOURCE,null)}var y=e.updateServerSnap(s,u.isFullyInitialized()||t.isEmpty(),l.filtersNodes()),v=new c.WriteTreeCompleteChildSource(r,y,i);return this.xr(y,t,r,v,a)},e.prototype.Ir=function(e,t,n,r,i,o){var a,u,l=e.getEventCache(),h=new c.WriteTreeCompleteChildSource(r,e,i);if(t.isEmpty())u=this.Rr.updateFullNode(e.getEventCache().getNode(),n,o),a=e.updateEventSnap(u,!0,this.Rr.filtersNodes());else{var p=t.getFront();if(".priority"===p)u=this.Rr.updatePriority(e.getEventCache().getNode(),n),a=e.updateEventSnap(u,l.isFullyInitialized(),l.isFiltered());else{var d=t.popFront(),f=l.getNode().getImmediateChild(p),_=void 0;if(d.isEmpty())_=n;else{var y=h.getCompleteChild(p);_=null!=y?".priority"===d.getBack()&&y.getChild(d.parent()).isEmpty()?y:y.updateChild(d,n):s.ChildrenNode.EMPTY_NODE}if(f.equals(_))a=e;else{var v=this.Rr.updateChild(l.getNode(),p,_,d,h,o);a=e.updateEventSnap(v,l.isFullyInitialized(),this.Rr.filtersNodes())}}}return a},e.kr=function(e,t){return e.getEventCache().isCompleteForChild(t)},e.prototype.Or=function(t,n,r,i,o,a){var s=this,u=t;return r.foreach(function(r,l){var h=n.child(r);e.kr(t,h.getFront())&&(u=s.Ir(u,h,l,i,o,a))}),r.foreach(function(r,l){var h=n.child(r);e.kr(t,h.getFront())||(u=s.Ir(u,h,l,i,o,a))}),u},e.prototype.Wr=function(e,t){return t.foreach(function(t,n){e=e.updateChild(t,n)}),e},e.prototype.Ar=function(e,t,n,r,i,o,a){var s=this;if(e.getServerCache().getNode().isEmpty()&&!e.getServerCache().isFullyInitialized())return e;var u,c=e;u=t.isEmpty()?n:l.ImmutableTree.Empty.setTree(t,n);var p=e.getServerCache().getNode();return u.children.inorderTraversal(function(t,n){if(p.hasChild(t)){var u=e.getServerCache().getNode().getImmediateChild(t),l=s.Wr(u,n);c=s.wr(c,new h.Path(t),l,r,i,o,a)}}),u.children.inorderTraversal(function(t,n){var u=!e.getServerCache().isCompleteForChild(t)&&null==n.value;if(!p.hasChild(t)&&!u){var l=e.getServerCache().getNode().getImmediateChild(t),d=s.Wr(l,n);c=s.wr(c,new h.Path(t),d,r,i,o,a)}}),c},e.prototype.Mr=function(e,t,n,r,i,o){if(null!=r.shadowingWrite(t))return e;var a=e.getServerCache().isFiltered(),s=e.getServerCache();if(null!=n.value){if(t.isEmpty()&&s.isFullyInitialized()||s.isCompleteForPath(t))return this.wr(e,t,s.getNode().getChild(t),r,i,a,o);if(t.isEmpty()){var c=l.ImmutableTree.Empty;return s.getNode().forEachChild(u.KEY_INDEX,function(e,t){c=c.set(new h.Path(e),t)}),this.Ar(e,t,c,r,i,a,o)}return e}var p=l.ImmutableTree.Empty;return n.foreach(function(e,n){var r=t.child(e);s.isCompleteForPath(r)&&(p=p.set(e,s.getNode().getChild(r)))}),this.Ar(e,t,p,r,i,a,o)},e.prototype.Lr=function(e,t,n,r){var i=e.getServerCache(),o=e.updateServerSnap(i.getNode(),i.isFullyInitialized()||t.isEmpty(),i.isFiltered());return this.xr(o,t,n,c.NO_COMPLETE_CHILD_SOURCE,r)},e.prototype.Dr=function(e,t,n,r,o){var a;if(null!=n.shadowingWrite(t))return e;var u=new c.WriteTreeCompleteChildSource(n,e,r),l=e.getEventCache().getNode(),p=void 0;if(t.isEmpty()||".priority"===t.getFront()){var d=void 0;if(e.getServerCache().isFullyInitialized())d=n.calcCompleteEventCache(e.getCompleteServerSnap());else{var f=e.getServerCache().getNode();i.assert(f instanceof s.ChildrenNode,"serverChildren would be complete if leaf node"),d=n.calcCompleteEventChildren(f)}d=d,p=this.Rr.updateFullNode(l,d,o)}else{var _=t.getFront(),y=n.calcCompleteChild(_,e.getServerCache());null==y&&e.getServerCache().isCompleteForChild(_)&&(y=l.getImmediateChild(_)),p=null!=y?this.Rr.updateChild(l,_,y,t.popFront(),u,o):e.getEventCache().getNode().hasChild(_)?this.Rr.updateChild(l,_,s.ChildrenNode.EMPTY_NODE,t.popFront(),u,o):l,p.isEmpty()&&e.getServerCache().isFullyInitialized()&&(a=n.calcCompleteEventCache(e.getCompleteServerSnap()),a.isLeafNode()&&(p=this.Rr.updateFullNode(p,a,o)))}return a=e.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(h.Path.Empty),e.updateEventSnap(p,a,this.Rr.filtersNodes())},e}();t.ViewProcessor=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(10),o=n(0),a=function(){function e(){this.Vr={}}return e.prototype.trackChildChange=function(e){var t=e.type,n=e.childName;o.assert(t==i.Change.CHILD_ADDED||t==i.Change.CHILD_CHANGED||t==i.Change.CHILD_REMOVED,"Only child changes supported for tracking"),o.assert(".priority"!==n,"Only non-priority child changes can be tracked.");var a=r.safeGet(this.Vr,n);if(a){var s=a.type;if(t==i.Change.CHILD_ADDED&&s==i.Change.CHILD_REMOVED)this.Vr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.snapshotNode);else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_ADDED)delete this.Vr[n];else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_CHANGED)this.Vr[n]=i.Change.childRemovedChange(n,a.oldSnap);else if(t==i.Change.CHILD_CHANGED&&s==i.Change.CHILD_ADDED)this.Vr[n]=i.Change.childAddedChange(n,e.snapshotNode);else{if(t!=i.Change.CHILD_CHANGED||s!=i.Change.CHILD_CHANGED)throw o.assertionError("Illegal combination of changes: "+e+" occurred after "+a);this.Vr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.oldSnap)}}else this.Vr[n]=e},e.prototype.getChanges=function(){return r.getValues(this.Vr)},e}();t.ChildChangeAccumulator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(20),i=function(){function e(){}return e.prototype.getCompleteChild=function(e){return null},e.prototype.getChildAfterChild=function(e,t,n){return null},e}();t.Qr=i,t.NO_COMPLETE_CHILD_SOURCE=new i;var o=function(){function e(e,t,n){void 0===n&&(n=null),this.qr=e,this.Sr=t,this.jr=n}return e.prototype.getCompleteChild=function(e){var t=this.Sr.getEventCache();if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.jr?new r.CacheNode(this.jr,!0,!1):this.Sr.getServerCache();return this.qr.calcCompleteChild(e,n)},e.prototype.getChildAfterChild=function(e,t,n){var r=null!=this.jr?this.jr:this.Sr.getCompleteServerSnap(),i=this.qr.calcIndexedSlice(r,t,1,n,e);return 0===i.length?null:i[0]},e}();t.WriteTreeCompleteChildSource=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),i=n(10),o=n(0),a=function(){function e(e){this.Er=e,this.Ee=this.Er.getQueryParams().getIndex()}return e.prototype.generateEventsForChanges=function(e,t,n){var r=this,o=[],a=[];return e.forEach(function(e){e.type===i.Change.CHILD_CHANGED&&r.Ee.indexedValueChanged(e.oldSnap,e.snapshotNode)&&a.push(i.Change.childMovedChange(e.childName,e.snapshotNode))}),this.Ur(o,i.Change.CHILD_REMOVED,e,n,t),this.Ur(o,i.Change.CHILD_ADDED,e,n,t),this.Ur(o,i.Change.CHILD_MOVED,a,n,t),this.Ur(o,i.Change.CHILD_CHANGED,e,n,t),this.Ur(o,i.Change.VALUE,e,n,t),o},e.prototype.Ur=function(e,t,n,r,i){var o=this,a=n.filter(function(e){return e.type===t});a.sort(this.Br.bind(this)),a.forEach(function(t){var n=o.Hr(t,i);r.forEach(function(r){r.respondsTo(t.type)&&e.push(r.createEvent(n,o.Er))})})},e.prototype.Hr=function(e,t){return"value"===e.type||"child_removed"===e.type?e:(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,this.Ee),e)},e.prototype.Br=function(e,t){if(null==e.childName||null==t.childName)throw o.assertionError("Should only compare child_ events.");var n=new r.NamedNode(e.childName,e.snapshotNode),i=new r.NamedNode(t.childName,t.snapshotNode);return this.Ee.compare(n,i)},e}();t.EventGenerator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(3),a=n(98),s=n(4),u=n(5),l=function(){function e(){this.Gr=a.CompoundWrite.Empty,this.Kr=[],this.Yr=-1}return e.prototype.childWrites=function(e){return new h(e,this)},e.prototype.addOverwrite=function(e,t,n,r){i.assert(n>this.Yr,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.Kr.push({path:e,snap:t,writeId:n,visible:r}),r&&(this.Gr=this.Gr.addWrite(e,t)),this.Yr=n},e.prototype.addMerge=function(e,t,n){i.assert(n>this.Yr,"Stacking an older merge on top of newer ones"),this.Kr.push({path:e,children:t,writeId:n,visible:!0}),this.Gr=this.Gr.addWrites(e,t),this.Yr=n},e.prototype.getWrite=function(e){for(var t=0;t=0,"removeWrite called with nonexistent writeId.");var o=this.Kr[n];this.Kr.splice(n,1);for(var a=o.visible,s=!1,u=this.Kr.length-1;a&&u>=0;){var l=this.Kr[u];l.visible&&(u>=n&&this.Xr(l,o.path)?a=!1:o.path.contains(l.path)&&(s=!0)),u--}if(a){if(s)return this.zr(),!0;if(o.snap)this.Gr=this.Gr.removeWrite(o.path);else{var h=o.children;r.forEach(h,function(e){t.Gr=t.Gr.removeWrite(o.path.child(e))})}return!0}return!1},e.prototype.getCompleteWriteData=function(e){return this.Gr.getCompleteNode(e)},e.prototype.calcCompleteEventCache=function(t,n,r,i){if(r||i){var a=this.Gr.childCompoundWrite(t);if(!i&&a.isEmpty())return n;if(i||null!=n||a.hasCompleteWrite(o.Path.Empty)){var s=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(e.path.contains(t)||t.contains(e.path))},l=e.Jr(this.Kr,s,t),h=n||u.ChildrenNode.EMPTY_NODE;return l.apply(h)}return null}var c=this.Gr.getCompleteNode(t);if(null!=c)return c;var p=this.Gr.childCompoundWrite(t);if(p.isEmpty())return n;if(null!=n||p.hasCompleteWrite(o.Path.Empty)){var h=n||u.ChildrenNode.EMPTY_NODE;return p.apply(h)}return null},e.prototype.calcCompleteEventChildren=function(e,t){var n=u.ChildrenNode.EMPTY_NODE,r=this.Gr.getCompleteNode(e);if(r)return r.isLeafNode()||r.forEachChild(s.PRIORITY_INDEX,function(e,t){n=n.updateImmediateChild(e,t)}),n;if(t){var i=this.Gr.childCompoundWrite(e);return t.forEachChild(s.PRIORITY_INDEX,function(e,t){var r=i.childCompoundWrite(new o.Path(e)).apply(t);n=n.updateImmediateChild(e,r)}),i.getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n}return this.Gr.childCompoundWrite(e).getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n},e.prototype.calcEventCacheAfterServerOverwrite=function(e,t,n,r){i.assert(n||r,"Either existingEventSnap or existingServerSnap must exist");var o=e.child(t);if(this.Gr.hasCompleteWrite(o))return null;var a=this.Gr.childCompoundWrite(o);return a.isEmpty()?r.getChild(t):a.apply(r.getChild(t))},e.prototype.calcCompleteChild=function(e,t,n){var r=e.child(t),i=this.Gr.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(t)?this.Gr.childCompoundWrite(r).apply(n.getNode().getImmediateChild(t)):null},e.prototype.shadowingWrite=function(e){return this.Gr.getCompleteNode(e)},e.prototype.calcIndexedSlice=function(e,t,n,r,i,a){var s,u=this.Gr.childCompoundWrite(e),l=u.getCompleteNode(o.Path.Empty);if(null!=l)s=l;else{if(null==t)return[];s=u.apply(t)}if(s=s.withIndex(a),s.isEmpty()||s.isLeafNode())return[];for(var h=[],c=a.getCompare(),p=i?s.getReverseIteratorFrom(n,a):s.getIteratorFrom(n,a),d=p.getNext();d&&h.length0?this.Yr=this.Kr[this.Kr.length-1].writeId:this.Yr=-1},e.$r=function(e){return e.visible},e.Jr=function(e,t,n){for(var s=a.CompoundWrite.Empty,u=0;u0&&r.contains(e.oi,t)&&(n[t]=i,o=!0)}),o&&this.Z.reportStats(n),i.setTimeoutNonBlocking(this.ai.bind(this),Math.floor(2*Math.random()*3e5))},e}();t.StatsReporter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(){this.si=[],this.ui=0}return e.prototype.queueEvents=function(e){for(var t=null,n=0;n0)return this.di[0];throw Error("No transports available")},e.prototype.upgradeTransport=function(){return this.di.length>1?this.di[1]:null},e}();t.TransportManager=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(e){this.Ht=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return e.prototype.closeAfter=function(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse=200&&h.status<300){try{e=a.jsonEval(h.responseText)}catch(e){o.warn("Failed to parse JSON response for "+l+": "+h.responseText)}n(null,e)}else 401!==h.status&&404!==h.status&&o.warn("Got unsuccessful REST response for "+l+" Status: "+h.status),n(h.status);n=null}},h.open("GET",l,!0),h.send()})},t}(l.ServerActions);t.ReadonlyRestClient=h},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(12),a=n(4),s=n(40),u=n(44),l=n(26),h=n(110),c=n(58),p=n(0),d=function(){function e(){this.yi=!1,this.vi=!1,this.gi=!1,this.mi=!1,this.Ci=!1,this.Ei=0,this.Ni="",this.Pi=null,this.Si="",this.bi=null,this.Ti="",this.Ee=a.PRIORITY_INDEX}return e.prototype.hasStart=function(){return this.vi},e.prototype.isViewFromLeft=function(){return""===this.Ni?this.vi:this.Ni===e.Ri.VIEW_FROM_LEFT},e.prototype.getIndexStartValue=function(){return r.assert(this.vi,"Only valid if start has been set"),this.Pi},e.prototype.getIndexStartName=function(){return r.assert(this.vi,"Only valid if start has been set"),this.gi?this.Si:i.MIN_NAME},e.prototype.hasEnd=function(){return this.mi},e.prototype.getIndexEndValue=function(){return r.assert(this.mi,"Only valid if end has been set"),this.bi},e.prototype.getIndexEndName=function(){return r.assert(this.mi,"Only valid if end has been set"),this.Ci?this.Ti:i.MAX_NAME},e.prototype.hasLimit=function(){return this.yi},e.prototype.hasAnchoredLimit=function(){return this.yi&&""!==this.Ni},e.prototype.getLimit=function(){return r.assert(this.yi,"Only valid if limit has been set"),this.Ei},e.prototype.getIndex=function(){return this.Ee},e.prototype.Ii=function(){var t=new e;return t.yi=this.yi,t.Ei=this.Ei,t.vi=this.vi,t.Pi=this.Pi,t.gi=this.gi,t.Si=this.Si,t.mi=this.mi,t.bi=this.bi,t.Ci=this.Ci,t.Ti=this.Ti,t.Ee=this.Ee,t.Ni=this.Ni,t},e.prototype.limit=function(e){var t=this.Ii();return t.yi=!0,t.Ei=e,t.Ni="",t},e.prototype.limitToFirst=function(t){var n=this.Ii();return n.yi=!0,n.Ei=t,n.Ni=e.Ri.VIEW_FROM_LEFT,n},e.prototype.limitToLast=function(t){var n=this.Ii();return n.yi=!0,n.Ei=t,n.Ni=e.Ri.VIEW_FROM_RIGHT,n},e.prototype.startAt=function(e,t){var n=this.Ii();return n.vi=!0,void 0===e&&(e=null),n.Pi=e,null!=t?(n.gi=!0,n.Si=t):(n.gi=!1,n.Si=""),n},e.prototype.endAt=function(e,t){var n=this.Ii();return n.mi=!0,void 0===e&&(e=null),n.bi=e,void 0!==t?(n.Ci=!0,n.Ti=t):(n.Ci=!1,n.Ti=""),n},e.prototype.orderBy=function(e){var t=this.Ii();return t.Ee=e,t},e.prototype.getQueryObject=function(){var t=e.Ri,n={};if(this.vi&&(n[t.INDEX_START_VALUE]=this.Pi,this.gi&&(n[t.INDEX_START_NAME]=this.Si)),this.mi&&(n[t.INDEX_END_VALUE]=this.bi,this.Ci&&(n[t.INDEX_END_NAME]=this.Ti)),this.yi){n[t.LIMIT]=this.Ei;var r=this.Ni;""===r&&(r=this.isViewFromLeft()?t.VIEW_FROM_LEFT:t.VIEW_FROM_RIGHT),n[t.VIEW_FROM]=r}return this.Ee!==a.PRIORITY_INDEX&&(n[t.INDEX]=""+this.Ee),n},e.prototype.loadsAllData=function(){return!(this.vi||this.mi||this.yi)},e.prototype.isDefault=function(){return this.loadsAllData()&&this.Ee==a.PRIORITY_INDEX},e.prototype.getNodeFilter=function(){return this.loadsAllData()?new l.IndexedFilter(this.getIndex()):this.hasLimit()?new h.LimitedFilter(this):new c.RangedFilter(this)},e.prototype.toRestQueryStringParameters=function(){var t=e.wi,n={};if(this.isDefault())return n;var i;return this.Ee===a.PRIORITY_INDEX?i=t.PRIORITY_INDEX:this.Ee===s.VALUE_INDEX?i=t.VALUE_INDEX:this.Ee===o.KEY_INDEX?i=t.KEY_INDEX:(r.assert(this.Ee instanceof u.PathIndex,"Unrecognized index type!"),i=""+this.Ee),n[t.ORDER_BY]=p.stringify(i),this.vi&&(n[t.START_AT]=p.stringify(this.Pi),this.gi&&(n[t.START_AT]+=","+p.stringify(this.Si))),this.mi&&(n[t.END_AT]=p.stringify(this.bi),this.Ci&&(n[t.END_AT]+=","+p.stringify(this.Ti))),this.yi&&(this.isViewFromLeft()?n[t.LIMIT_TO_FIRST]=this.Ei:n[t.LIMIT_TO_LAST]=this.Ei),n},e.Ri={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},e.wi={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},e.DEFAULT=new e,e}();t.QueryParams=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(58),i=n(5),o=n(6),a=n(0),s=n(10),u=function(){function e(e){this.Oi=new r.RangedFilter(e),this.Ee=e.getIndex(),this.Ei=e.getLimit(),this.Ai=!e.isViewFromLeft()}return e.prototype.updateChild=function(e,t,n,r,a,s){return this.Oi.matches(new o.NamedNode(t,n))||(n=i.ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()=0)return null!=u&&u.trackChildChange(s.Change.childChangedChange(t,n,_)),c.updateImmediateChild(t,n);null!=u&&u.trackChildChange(s.Change.childRemovedChange(t,_));var g=c.updateImmediateChild(t,i.ChildrenNode.EMPTY_NODE);return null!=y&&this.Oi.matches(y)?(null!=u&&u.trackChildChange(s.Change.childAddedChange(y.name,y.node)),g.updateImmediateChild(y.name,y.node)):g}return n.isEmpty()?e:f&&l(d,p)>=0?(null!=u&&(u.trackChildChange(s.Change.childRemovedChange(d.name,d.node)),u.trackChildChange(s.Change.childAddedChange(t,n))),c.updateImmediateChild(t,n).updateImmediateChild(d.name,i.ChildrenNode.EMPTY_NODE)):e},e}();t.LimitedFilter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i=n(0),o=n(23),a=n(24),s=n(3),u=n(112),l=n(4),h=n(1),c=n(45),p=n(8),d=n(0),f=n(13),_=n(5),y=n(19);!function(e){e[e.RUN=0]="RUN",e[e.SENT=1]="SENT",e[e.COMPLETED=2]="COMPLETED",e[e.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",e[e.NEEDS_ABORT=4]="NEEDS_ABORT"}(r=t.TransactionStatus||(t.TransactionStatus={})),y.Repo.Mi=25,y.Repo.prototype.ie=function(){this.Li=new u.Tree},y.Repo.prototype.startTransaction=function(e,t,n,s){this.de("transaction on "+e);var u=function(){},y=new o.Reference(this,e);y.on("value",u);var v=function(){y.off("value",u)},g={path:e,update:t,onComplete:n,status:null,order:h.LUIDGenerator(),applyLocally:s,retryCount:0,unwatcher:v,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},m=this.Fi(e);g.currentInputSnapshot=m;var C=g.update(m.val());if(void 0===C){if(g.unwatcher(),g.currentOutputSnapshotRaw=null,g.currentOutputSnapshotResolved=null,g.onComplete){var E=new a.DataSnapshot(g.currentInputSnapshot,new o.Reference(this,g.path),l.PRIORITY_INDEX);g.onComplete(null,!1,E)}}else{p.validateFirebaseData("transaction failed: Data returned ",C,g.path),g.status=r.RUN;var N=this.Li.subTree(e),P=N.getValue()||[];P.push(g),N.setValue(P);var S=void 0;"object"==typeof C&&null!==C&&d.contains(C,".priority")?(S=d.safeGet(C,".priority"),i.assert(p.isValidPriority(S),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):S=(this.ue.calcCompleteEventCache(e)||_.ChildrenNode.EMPTY_NODE).getPriority().val(),S=S;var b=this.generateServerValues(),T=f.nodeFromJSON(C,S),R=c.resolveDeferredValueSnapshot(T,b);g.currentOutputSnapshotRaw=T,g.currentOutputSnapshotResolved=R,g.currentWriteId=this.pe();var I=this.ue.applyUserOverwrite(e,R,g.currentWriteId,g.applyLocally);this.K.raiseEventsForChangedPath(e,I),this.xi()}},y.Repo.prototype.Fi=function(e,t){return this.ue.calcCompleteEventCache(e,t)||_.ChildrenNode.EMPTY_NODE},y.Repo.prototype.xi=function(e){var t=this;if(void 0===e&&(e=this.Li),e||this.ki(e),null!==e.getValue()){var n=this.Wi(e);i.assert(n.length>0,"Sending zero length transaction queue"),n.every(function(e){return e.status===r.RUN})&&this.Vi(e.path(),n)}else e.hasChildren()&&e.forEachChild(function(e){t.xi(e)})},y.Repo.prototype.Vi=function(e,t){for(var n=this,u=t.map(function(e){return e.currentWriteId}),c=this.Fi(e,u),p=c,d=c.hash(),f=0;f=y.Repo.Mi)E=!0,N="maxretry",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0));else{var P=this.Fi(m.path,v);m.currentInputSnapshot=P;var S=e[g].update(P.val());if(void 0!==S){p.validateFirebaseData("transaction failed: Data returned ",S,m.path);var b=f.nodeFromJSON(S),T="object"==typeof S&&null!=S&&d.contains(S,".priority");T||(b=b.updatePriority(P.getPriority()));var R=m.currentWriteId,I=this.generateServerValues(),w=c.resolveDeferredValueSnapshot(b,I);m.currentOutputSnapshotRaw=b,m.currentOutputSnapshotResolved=w,m.currentWriteId=this.pe(),v.splice(v.indexOf(R),1),u=u.concat(this.ue.applyUserOverwrite(m.path,w,m.currentWriteId,m.applyLocally)),u=u.concat(this.ue.ackUserWrite(R,!0))}else E=!0,N="nodata",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0))}if(this.K.raiseEventsForChangedPath(t,u),u=[],E&&(e[g].status=r.COMPLETED,function(e){setTimeout(e,Math.floor(0))}(e[g].unwatcher),e[g].onComplete))if("nodata"===N){var O=new o.Reference(this,e[g].path),A=e[g].currentInputSnapshot,D=new a.DataSnapshot(A,O,l.PRIORITY_INDEX);n.push(e[g].onComplete.bind(null,null,!1,D))}else n.push(e[g].onComplete.bind(null,Error(N),!1,null))}this.ki(this.Li);for(var g=0;g0?n:null)}e.forEachChild(function(e){t.ki(e)})},y.Repo.prototype.fe=function(e){var t=this,n=this.Qi(e).path(),r=this.Li.subTree(e);return r.forEachAncestor(function(e){t.Ui(e)}),this.Ui(r),r.forEachDescendant(function(e){t.Ui(e)}),n},y.Repo.prototype.Ui=function(e){var t=e.getValue();if(null!==t){for(var n=[],o=[],a=-1,s=0;s0},e.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},e.prototype.forEachChild=function(t){var n=this;o.forEach(this._e.children,function(r,i){t(new e(r,n,i))})},e.prototype.forEachDescendant=function(e,t,n){t&&!n&&e(this),this.forEachChild(function(t){t.forEachDescendant(e,!0,n)}),t&&n&&e(this)},e.prototype.forEachAncestor=function(e,t){for(var n=t?this:this.parent();null!==n;){if(e(n))return!0;n=n.parent()}return!1},e.prototype.forEachImmediateDescendantWithValue=function(e){this.forEachChild(function(t){null!==t.getValue()?e(t):t.forEachImmediateDescendantWithValue(e)})},e.prototype.path=function(){return new i.Path(null===this.Hi?this.Bi:this.Hi.path()+"/"+this.Bi)},e.prototype.name=function(){return this.Bi},e.prototype.parent=function(){return this.Hi},e.prototype.Gi=function(){null!==this.Hi&&this.Hi.Ki(this.Bi,this)},e.prototype.Ki=function(e,t){var n=t.isEmpty(),r=o.contains(this._e.children,e);n&&r?(delete this._e.children[e],this._e.childCount--,this.Gi()):n||r||(this._e.children[e]=t._e,this._e.childCount++,this.Gi())},e}();t.Tree=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(56),i=n(55);t.forceLongPolling=function(){r.WebSocketConnection.forceDisallow(),i.BrowserPollConnection.forceAllow()},t.forceWebSockets=function(){i.BrowserPollConnection.forceDisallow()},t.isWebSocketsAvailable=function(){return r.WebSocketConnection.isAvailable()},t.setSecurityDebugCallback=function(e,t){e.repo.J.at=t},t.stats=function(e,t){e.repo.stats(t)},t.statsIncrementCounter=function(e,t){e.repo.statsIncrementCounter(t)},t.dataUpdateCount=function(e){return e.repo.dataUpdateCount},t.interceptServerData=function(e,t){return e.repo.he(t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(36),i=n(52),o=n(28),a=n(54);t.DataConnection=i.PersistentConnection,i.PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},i.PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},t.RealTimeConnection=a.Connection,t.hijackHash=function(e){var t=i.PersistentConnection.prototype.put;return i.PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){i.PersistentConnection.prototype.put=t}},t.ConnectionTarget=r.RepoInfo,t.queryIdentifier=function(e){return e.queryIdentifier()},t.listens=function(e){return e.repo.J.Ze},t.forceRestClient=function(e){o.RepoManager.getInstance().forceRestClient(e)}}],[80])}catch(e){throw Error("Cannot instantiate firebase-database.js - be sure to load firebase-app.js first.")} /*! - * @license Firebase v4.6.1 - * Build: rev-0ea11f2 + * @license Firebase v4.12.0 + * Build: rev-ef14d4f * Terms: https://firebase.google.com/terms/ */ -try{webpackJsonpFirebase([3],{116:function(e,t,r){r(117)},117:function(e,t,r){"use strict";function n(e){var t=new Uint8Array(e);return window.btoa(String.fromCharCode.apply(null,t))}function o(e){var t=function(e){return self&&"ServiceWorkerGlobalScope"in self?new A(e):new k(e)},r={Messaging:k};e.INTERNAL.registerService("messaging",t,r)}Object.defineProperty(t,"__esModule",{value:!0});var i,s=r(0),a={AVAILABLE_IN_WINDOW:"only-available-in-window",AVAILABLE_IN_SW:"only-available-in-sw",SHOULD_BE_INHERITED:"should-be-overriden",BAD_SENDER_ID:"bad-sender-id",INCORRECT_GCM_SENDER_ID:"incorrect-gcm-sender-id",PERMISSION_DEFAULT:"permission-default",PERMISSION_BLOCKED:"permission-blocked",UNSUPPORTED_BROWSER:"unsupported-browser",NOTIFICATIONS_BLOCKED:"notifications-blocked",FAILED_DEFAULT_REGISTRATION:"failed-serviceworker-registration",SW_REGISTRATION_EXPECTED:"sw-registration-expected",GET_SUBSCRIPTION_FAILED:"get-subscription-failed",INVALID_SAVED_TOKEN:"invalid-saved-token",SW_REG_REDUNDANT:"sw-reg-redundant",TOKEN_SUBSCRIBE_FAILED:"token-subscribe-failed",TOKEN_SUBSCRIBE_NO_TOKEN:"token-subscribe-no-token",TOKEN_SUBSCRIBE_NO_PUSH_SET:"token-subscribe-no-push-set",USE_SW_BEFORE_GET_TOKEN:"use-sw-before-get-token",INVALID_DELETE_TOKEN:"invalid-delete-token",DELETE_TOKEN_NOT_FOUND:"delete-token-not-found",DELETE_SCOPE_NOT_FOUND:"delete-scope-not-found",BG_HANDLER_FUNCTION_EXPECTED:"bg-handler-function-expected",NO_WINDOW_CLIENT_TO_MSG:"no-window-client-to-msg",UNABLE_TO_RESUBSCRIBE:"unable-to-resubscribe",NO_FCM_TOKEN_FOR_RESUBSCRIBE:"no-fcm-token-for-resubscribe",FAILED_TO_DELETE_TOKEN:"failed-to-delete-token",NO_SW_IN_REG:"no-sw-in-reg",BAD_SCOPE:"bad-scope",BAD_VAPID_KEY:"bad-vapid-key",BAD_SUBSCRIPTION:"bad-subscription",BAD_TOKEN:"bad-token",BAD_PUSH_SET:"bad-push-set",FAILED_DELETE_VAPID_KEY:"failed-delete-vapid-key"},c=(i={},i[a.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",i[a.AVAILABLE_IN_SW]="This method is available in a service worker context.",i["should-be-overriden"]="This method should be overriden by extended classes.",i["bad-sender-id"]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",i["permission-default"]="The required permissions were not granted and dismissed instead.",i["permission-blocked"]="The required permissions were not granted and blocked instead.",i["unsupported-browser"]="This browser doesn't support the API's required to use the firebase SDK.",i["notifications-blocked"]="Notifications have been blocked.",i[a.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",i["sw-registration-expected"]="A service worker registration was the expected input.",i["get-subscription-failed"]="There was an error when trying to get any existing Push Subscriptions.",i["invalid-saved-token"]="Unable to access details of the saved token.",i["sw-reg-redundant"]="The service worker being used for push was made redundant.",i["token-subscribe-failed"]="A problem occured while subscribing the user to FCM: {$message}",i["token-subscribe-no-token"]="FCM returned no token when subscribing the user to push.",i["token-subscribe-no-push-set"]="FCM returned an invalid response when getting an FCM token.",i["use-sw-before-get-token"]="You must call useServiceWorker() before calling getToken() to ensure your service worker is used.",i["invalid-delete-token"]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",i["delete-token-not-found"]="The deletion attempt for token could not be performed as the token was not found.",i["delete-scope-not-found"]="The deletion attempt for service worker scope could not be performed as the scope was not found.",i["bg-handler-function-expected"]="The input to setBackgroundMessageHandler() must be a function.",i["no-window-client-to-msg"]="An attempt was made to message a non-existant window client.",i["unable-to-resubscribe"]="There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}",i["no-fcm-token-for-resubscribe"]="Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit.",i["failed-to-delete-token"]="Unable to delete the currently saved token.",i["no-sw-in-reg"]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",i["incorrect-gcm-sender-id"]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",i["bad-scope"]="The service worker scope must be a string with at least one character.",i["bad-vapid-key"]="The public VAPID key must be a string with at least one character.",i["bad-subscription"]="The subscription must be a valid PushSubscription.",i["bad-token"]="The FCM Token used for storage / lookup was not a valid token string.",i["bad-push-set"]="The FCM push set used for storage / lookup was not not a valid push set string.",i["failed-delete-vapid-key"]="The VAPID key could not be deleted.",i),u={codes:a,map:c},_=function(e){return n(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},d=[4,51,148,247,223,161,235,177,220,3,162,94,21,113,219,72,211,46,237,237,178,52,219,183,71,58,12,143,196,204,225,111,60,140,132,223,171,182,102,62,242,12,212,139,254,227,249,118,47,20,28,99,8,106,111,45,177,26,149,176,206,55,192,156,110],f={userVisibleOnly:!0,applicationServerKey:new Uint8Array(d)},h={ENDPOINT:"https://fcm.googleapis.com",APPLICATION_SERVER_KEY:d,SUBSCRIPTION_OPTIONS:f},p="fcm_token_object_Store",l=function(){function e(){this.e=new s.ErrorFactory("messaging","Messaging",u.map),this.t=null}return e.prototype.r=function(){return this.t?this.t:(this.t=new Promise(function(t,r){var n=indexedDB.open(e.DB_NAME,1);n.onerror=function(e){r(e.target.error)},n.onsuccess=function(e){t(e.target.result)},n.onupgradeneeded=function(e){var t=e.target.result,r=t.createObjectStore(p,{keyPath:"swScope"});r.createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0})}}),this.t)},e.prototype.closeDatabase=function(){var e=this;return this.t?this.t.then(function(t){t.close(),e.t=null}):Promise.resolve()},e.prototype.getTokenDetailsFromToken=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.index("fcmToken"),a=s.get(e);a.onerror=function(e){n(e.target.error)},a.onsuccess=function(e){r(e.target.result)}})})},e.prototype.n=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.get(e);s.onerror=function(e){n(e.target.error)},s.onsuccess=function(e){r(e.target.result)}})})},e.prototype.o=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=[],a=i.openCursor();a.onerror=function(e){n(e.target.error)},a.onsuccess=function(t){var n=t.target.result;n?(n.value.fcmSenderId===e&&s.push(n.value),n.continue()):r(s)}})})},e.prototype.subscribeToFCM=function(e,t,r){var n=this,o=_(t.getKey("p256dh")),i=_(t.getKey("auth")),s="authorized_entity="+e+"&endpoint="+t.endpoint+"&encryption_key="+o+"&encryption_auth="+i;r&&(s+="&pushSet="+r);var a=new Headers;a.append("Content-Type","application/x-www-form-urlencoded");var c={method:"POST",headers:a,body:s};return fetch(h.ENDPOINT+"/fcm/connect/subscribe",c).then(function(e){return e.json()}).then(function(e){var t=e;if(t.error){var r=t.error.message;throw n.e.create(u.codes.TOKEN_SUBSCRIBE_FAILED,{message:r})}if(!t.token)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_TOKEN);if(!t.pushSet)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);return{token:t.token,pushSet:t.pushSet}})},e.prototype.i=function(e,t){return e.endpoint===t.endpoint&&_(e.getKey("auth"))===t.auth&&_(e.getKey("p256dh"))===t.p256dh},e.prototype.s=function(e,t,r,n,o){var i={swScope:t.scope,endpoint:r.endpoint,auth:_(r.getKey("auth")),p256dh:_(r.getKey("p256dh")),fcmToken:n,fcmPushSet:o,fcmSenderId:e};return this.r().then(function(e){return new Promise(function(t,r){var n=e.transaction([p],"readwrite"),o=n.objectStore(p),s=o.put(i);s.onerror=function(e){r(e.target.error)},s.onsuccess=function(e){t()}})})},e.prototype.getSavedToken=function(e,t){var r=this;return t instanceof ServiceWorkerRegistration?"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.BAD_SENDER_ID)):this.o(e).then(function(r){if(0!==r.length){var n=r.findIndex(function(r){return t.scope===r.swScope&&e===r.fcmSenderId});if(-1!==n)return r[n]}}).then(function(e){if(e)return t.pushManager.getSubscription().catch(function(e){throw r.e.create(u.codes.GET_SUBSCRIPTION_FAILED)}).then(function(t){if(t&&r.i(t,e))return e.fcmToken})}):Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED))},e.prototype.createToken=function(e,t){var r=this;if("string"!=typeof e||0===e.length)return Promise.reject(this.e.create(u.codes.BAD_SENDER_ID));if(!(t instanceof ServiceWorkerRegistration))return Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED));var n,o;return t.pushManager.getSubscription().then(function(e){return e||t.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(t){return n=t,r.subscribeToFCM(e,n)}).then(function(i){return o=i,r.s(e,t,n,o.token,o.pushSet)}).then(function(){return o.token})},e.prototype.deleteToken=function(e){var t=this;return"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.INVALID_DELETE_TOKEN)):this.getTokenDetailsFromToken(e).then(function(e){if(!e)throw t.e.create(u.codes.DELETE_TOKEN_NOT_FOUND);return t.r().then(function(r){return new Promise(function(n,o){var i=r.transaction([p],"readwrite"),s=i.objectStore(p),a=s.delete(e.swScope);a.onerror=function(e){o(e.target.error)},a.onsuccess=function(r){if(0===r.target.result)return void o(t.e.create(u.codes.FAILED_TO_DELETE_TOKEN));n(e)}})})})},e}(),g=l,E="messagingSenderId",T=function(){function e(e){var t=this;if(this.e=new s.ErrorFactory("messaging","Messaging",u.map),!e.options[E]||"string"!=typeof e.options[E])throw this.e.create(u.codes.BAD_SENDER_ID);this.a=e.options[E],this.c=new g,this.app=e,this.INTERNAL={},this.INTERNAL.delete=function(){return t.delete}}return e.prototype.getToken=function(){var e=this,t=this.u();return"granted"!==t?"denied"===t?Promise.reject(this.e.create(u.codes.NOTIFICATIONS_BLOCKED)):Promise.resolve(null):this._().then(function(t){return e.c.getSavedToken(e.a,t).then(function(r){return r||e.c.createToken(e.a,t)})})},e.prototype.deleteToken=function(e){var t=this;return this.c.deleteToken(e).then(function(){return t._().then(function(e){if(e)return e.pushManager.getSubscription()}).then(function(e){if(e)return e.unsubscribe()})})},e.prototype._=function(){throw this.e.create(u.codes.SHOULD_BE_INHERITED)},e.prototype.requestPermission=function(){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.useServiceWorker=function(e){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onMessage=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onTokenRefresh=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.setBackgroundMessageHandler=function(e){throw this.e.create(u.codes.AVAILABLE_IN_SW)},e.prototype.delete=function(){return this.c.closeDatabase()},e.prototype.u=function(){return Notification.permission},e.prototype.getTokenManager=function(){return this.c},e}(),S=T,b={TYPE_OF_MSG:"firebase-messaging-msg-type",DATA:"firebase-messaging-msg-data"},v={PUSH_MSG_RECEIVED:"push-msg-received",NOTIFICATION_CLICKED:"notification-clicked"},I=function(e,t){return r={},r[b.TYPE_OF_MSG]=e,r[b.DATA]=t,r;var r},m={PARAMS:b,TYPES_OF_MSG:v,createNewMsg:I},y={path:"/firebase-messaging-sw.js",scope:"/firebase-cloud-messaging-push-scope"},N=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),w=function(e){function t(t){var r=e.call(this,t)||this;return r.d,r.f,r.h=null,r.p=Object(s.createSubscribe)(function(e){r.h=e}),r.l=null,r.g=Object(s.createSubscribe)(function(e){r.l=e}),r.T(),r}return N(t,e),t.prototype.getToken=function(){var t=this;return this.S()?this.b().then(function(){return e.prototype.getToken.call(t)}):Promise.reject(this.e.create(u.codes.UNSUPPORTED_BROWSER))},t.prototype.b=function(){var e=this;if(this.f)return this.f;var t=document.querySelector('link[rel="manifest"]');return this.f=t?fetch(t.href).then(function(e){return e.json()}).catch(function(){return Promise.resolve()}).then(function(t){if(t&&t.gcm_sender_id&&"103953800507"!==t.gcm_sender_id)throw e.e.create(u.codes.INCORRECT_GCM_SENDER_ID)}):Promise.resolve(),this.f},t.prototype.requestPermission=function(){var e=this;return"granted"===Notification.permission?Promise.resolve():new Promise(function(t,r){var n=function(n){return"granted"===n?t():r("denied"===n?e.e.create(u.codes.PERMISSION_BLOCKED):e.e.create(u.codes.PERMISSION_DEFAULT))},o=Notification.requestPermission(function(e){o||n(e)});o&&o.then(n)})},t.prototype.useServiceWorker=function(e){if(!(e instanceof ServiceWorkerRegistration))throw this.e.create(u.codes.SW_REGISTRATION_EXPECTED);if(void 0!==this.d)throw this.e.create(u.codes.USE_SW_BEFORE_GET_TOKEN);this.d=e},t.prototype.onMessage=function(e,t,r){return this.p(e,t,r)},t.prototype.onTokenRefresh=function(e,t,r){return this.g(e,t,r)},t.prototype.v=function(e){var t=this,r=e.installing||e.waiting||e.active;return new Promise(function(n,o){if(!r)return void o(t.e.create(u.codes.NO_SW_IN_REG));if("activated"===r.state)return void n(e);if("redundant"===r.state)return void o(t.e.create(u.codes.SW_REG_REDUNDANT));var i=function(){if("activated"===r.state)n(e);else{if("redundant"!==r.state)return;o(t.e.create(u.codes.SW_REG_REDUNDANT))}r.removeEventListener("statechange",i)};r.addEventListener("statechange",i)})},t.prototype._=function(){var e=this;return this.d?this.v(this.d):(this.d=null,navigator.serviceWorker.register(y.path,{scope:y.scope}).catch(function(t){throw e.e.create(u.codes.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:t.message})}).then(function(t){return e.v(t).then(function(){return e.d=t,t.update(),t})}))},t.prototype.T=function(){var e=this;"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",function(t){if(t.data&&t.data[m.PARAMS.TYPE_OF_MSG]){var r=t.data;switch(r[m.PARAMS.TYPE_OF_MSG]){case m.TYPES_OF_MSG.PUSH_MSG_RECEIVED:case m.TYPES_OF_MSG.NOTIFICATION_CLICKED:var n=r[m.PARAMS.DATA];e.h.next(n)}}},!1)},t.prototype.S=function(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")},t}(S),k=w,O=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),D=function(e){function t(t){var r=e.call(this,t)||this;return self.addEventListener("push",function(e){return r.I(e)},!1),self.addEventListener("pushsubscriptionchange",function(e){return r.m(e)},!1),self.addEventListener("notificationclick",function(e){return r.y(e)},!1),r.N=null,r}return O(t,e),t.prototype.I=function(e){var t,r=this;try{t=e.data.json()}catch(e){return}var n=this.w().then(function(e){if(e){if(t.notification||r.N)return r.k(t)}else{var n=r.O(t);if(n){var o=n.title||"";return self.registration.showNotification(o,n)}if(r.N)return r.N(t)}});e.waitUntil(n)},t.prototype.m=function(e){var t=this,r=this.getToken().then(function(e){if(!e)throw t.e.create(u.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);var r=null,n=t.getTokenManager();return n.getTokenDetailsFromToken(e).then(function(e){if(!(r=e))throw t.e.create(u.codes.INVALID_SAVED_TOKEN);return self.registration.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(e){return n.subscribeToFCM(r.fcmSenderId,e,r.fcmPushSet)}).catch(function(e){return n.deleteToken(r.fcmToken).then(function(){throw t.e.create(u.codes.UNABLE_TO_RESUBSCRIBE,{message:e})})})});e.waitUntil(r)},t.prototype.y=function(e){var t=this;if(e.notification&&e.notification.data&&e.notification.data.FCM_MSG){e.stopImmediatePropagation(),e.notification.close();var r=e.notification.data.FCM_MSG,n=r.notification.click_action;if(n){var o=this.D(n).then(function(e){return e||self.clients.openWindow(n)}).then(function(e){if(e){r.notification,delete r.notification;var n=m.createNewMsg(m.TYPES_OF_MSG.NOTIFICATION_CLICKED,r);return t.A(e,n)}});e.waitUntil(o)}}},t.prototype.O=function(e){if(e&&"object"==typeof e.notification){var t=Object.assign({},e.notification);return t.data=(r={},r.FCM_MSG=e,r),t;var r}},t.prototype.setBackgroundMessageHandler=function(e){if(e&&"function"!=typeof e)throw this.e.create(u.codes.BG_HANDLER_FUNCTION_EXPECTED);this.N=e},t.prototype.D=function(e){var t=new URL(e).href;return self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(function(e){for(var r=null,n=0;n>6,128|63&r);else if(55296==(64512&r)){var o=n>18,128|r>>12&63,128|r>>6&63,128|63&r)}else e.push(239,191,189)}else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function T(t){var e;try{e=decodeURIComponent(t)}catch(t){throw y(ne.DATA_URL,"Malformed data URL.")}return U(e)}function A(t,e){switch(t){case ne.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r){var o=n?"-":"_";throw y(t,"Invalid character '"+o+"' found: is it base64url encoded?")}break;case ne.BASE64URL:var i=-1!==e.indexOf("+"),a=-1!==e.indexOf("/");if(i||a){var o=i?"+":"/";throw y(t,"Invalid character '"+o+"' found: is it base64 encoded?")}e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw y(t,"Invalid character found")}for(var u=new Uint8Array(s.length),c=0;c=e.length)&&t.substring(t.length-e.length)===e}function S(t){switch(t){case ae.RUNNING:case ae.PAUSING:case ae.CANCELING:return se.RUNNING;case ae.PAUSED:return se.PAUSED;case ae.SUCCESS:return se.SUCCESS;case ae.CANCELED:return se.CANCELED;case ae.ERROR:default:return se.ERROR}}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function I(t,e){for(var n in t)k(t,n)&&e(n,t[n])}function L(t){if(null==t)return{};var e={};return I(t,function(t,n){e[t]=n}),e}function P(t){return new Promise(t)}function x(t){return Promise.resolve(t)}function D(t){return Promise.reject(t)}function M(t){return null!=t}function W(t){return void 0!==t}function B(t){return"function"==typeof t}function G(t){return"object"==typeof t}function j(t){return G(t)&&null!==t}function q(t){return G(t)&&!Array.isArray(t)}function F(t){return"string"==typeof t||t instanceof String}function H(t){return"number"==typeof t||t instanceof Number}function z(t){return X()&&t instanceof Blob}function X(){return"undefined"!=typeof Blob}function V(t){var e;try{e=JSON.parse(t)}catch(t){return null}return q(e)?e:null}function K(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}function Z(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}function J(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Q(t){return Vt+Zt+t}function Y(t){return Kt+Zt+t}function $(t){return Vt+Jt+t}function tt(t){var e=encodeURIComponent,n="?";return I(t,function(t,r){var o=e(t)+"="+e(r);n=n+o+"&"}),n=n.slice(0,-1)}function et(t,e){return e}function nt(t){return!F(t)||t.length<2?t:(t=t,J(t))}function rt(){function t(t,e){return nt(e)}function e(t,e){return M(e)?+e:e}function n(t,e){if(!(F(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,o=t.fullPath;return Y("/b/"+n(r)+"/o/"+n(o))+tt({alt:"media",token:e})})}if(pe)return pe;var r=[];r.push(new he("bucket")),r.push(new he("generation")),r.push(new he("metageneration")),r.push(new he("name","fullPath",!0));var o=new he("name");o.xform=t,r.push(o);var i=new he("size");return i.xform=e,r.push(i),r.push(new he("timeCreated")),r.push(new he("updated")),r.push(new he("md5Hash",null,!0)),r.push(new he("cacheControl",null,!0)),r.push(new he("contentDisposition",null,!0)),r.push(new he("contentEncoding",null,!0)),r.push(new he("contentLanguage",null,!0)),r.push(new he("contentType",null,!0)),r.push(new he("metadata","customMetadata",!0)),r.push(new he("downloadTokens","downloadURLs",!1,n)),pe=r}function ot(t,e){function n(){var n=t.bucket,r=t.fullPath,o=new le(n,r);return e.makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function it(t,e,n){var r={};r.type="file";for(var o=n.length,i=0;i=0))throw"Expected a number 0 or greater."}return new fe(t)}function _t(t,e){function n(e){if(!(null===e||M(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)}return new fe(n,e)}function vt(t){function e(t){if(null!==t&&!B(t))throw"Expected a Function."}return new fe(e,t)}function bt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function mt(){for(var t=[],e=0;e0&&(h=Math.min(h,o));var p=c.current,_=p+h,v=h===l?"upload, finalize":"upload",b={"X-Goog-Upload-Command":v,"X-Goog-Upload-Offset":c.current},m=r.slice(p,_);if(null===m)throw f();var g=e.maxUploadRetryTime(),y=new _e(n,"POST",u,g);return y.headers=b,y.body=m.uploadData(),y.progressCallback=s||null,y.errorHandler=Tt(t),y}function Mt(t){return function(){for(var e=[],n=0;n0&&(t.Authorization="Firebase "+e)}function jt(t){var e=void 0!==Xt.default?Xt.default.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}function qt(t,e,n){var r=tt(t.urlParams),o=t.url+r,i=L(t.headers);return Gt(i,e),jt(i),new Ue(o,t.method,i,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}function Ft(t,e,n){return new Ae(t,new ce,n)}function Ht(t){var e={TaskState:se,TaskEvent:ie,StringFormat:ne,Storage:Ae,Reference:ye};t.INTERNAL.registerService(Oe,Ft,e,void 0,!0)}Object.defineProperty(e,"__esModule",{value:!0});var zt,Xt=n(6),Vt="https://firebasestorage.googleapis.com",Kt="https://firebasestorage.googleapis.com",Zt="/v0",Jt="/v0",Qt=12e4,Yt=6e4,$t=-9007199254740991,te=function(){function t(t,e){this.t=r(t),this.e="Firebase Storage: "+e,this.n=null,this.r="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return r(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.n},t.prototype.setServerResponseProp=function(t){this.n=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.r},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.n},enumerable:!0,configurable:!0}),t}(),ee={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"},ne={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},re=function(){function t(t,e){this.data=t,this.contentType=e||null}return t}(),oe=function(){function t(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw y(ne.DATA_URL,"Must be formatted 'data:[][;base64],");var n=e[1]||null;null!=n&&(this.base64=C(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=t.substring(t.indexOf(",")+1)}return t}(),ie={STATE_CHANGED:"state_changed"},ae={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},se={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(zt=zt||(zt={}));var ue=function(){function t(){var t=this;this.o=!1,this.i=new XMLHttpRequest,this.a=zt.NO_ERROR,this.s=P(function(e,n){t.i.addEventListener("abort",function(n){t.a=zt.ABORT,e(t)}),t.i.addEventListener("error",function(n){t.a=zt.NETWORK_ERROR,e(t)}),t.i.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var o=this;if(this.o)throw R("cannot .send() more than once");return this.o=!0,this.i.open(e,t,!0),M(r)&&I(r,function(t,e){o.i.setRequestHeader(t,""+e)}),M(n)?this.i.send(n):this.i.send(),this.s},t.prototype.getErrorCode=function(){if(!this.o)throw R("cannot .getErrorCode() before sending");return this.a},t.prototype.getStatus=function(){if(!this.o)throw R("cannot .getStatus() before sending");try{return this.i.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.o)throw R("cannot .getResponseText() before sending");return this.i.responseText},t.prototype.abort=function(){this.i.abort()},t.prototype.getResponseHeader=function(t){return this.i.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.removeEventListener("progress",t)},t}(),ce=function(){function t(){}return t.prototype.createXhrIo=function(){return new ue},t}(),le=function(){function t(t,e){this.bucket=t,this.u=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.u},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw p(e)},t.makeFromUrl=function(e){function n(t){"/"===t.path.charAt(t.path.length-1)&&(t.u=t.u.slice(0,-1))}function r(t){t.u=decodeURIComponent(t.path)}for(var o=null,i=RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),a={bucket:1,path:3},s=RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),u={bucket:1,path:3},c=[{regex:i,indices:a,postModify:n},{regex:s,indices:u,postModify:r}],l=0;l262144},t.prototype.M=function(){this.k===ae.RUNNING&&null===this.m&&(this.C?null===this.b?this.G():this.f?this.j():this.d?this.q():this.F():this.H())},t.prototype.z=function(t){var e=this;this.U.getAuthToken().then(function(n){switch(e.k){case ae.RUNNING:t(n);break;case ae.CANCELING:e.P(ae.CANCELED);break;case ae.PAUSING:e.P(ae.PAUSED)}})},t.prototype.G=function(){var t=this;this.z(function(e){var n=Pt(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.b=e,t.f=!1,t.L()},t.I)})},t.prototype.j=function(){var t=this,e=this.b;this.z(function(n){var r=xt(t.U,t.T,e,t.A),o=t.U.makeRequest(r,n);t.m=o,o.getPromise().then(function(e){e=e,t.m=null,t.B(e.current),t.f=!1,e.finalized&&(t.d=!0),t.L()},t.I)})},t.prototype.F=function(){var t=this,e=262144*this.g,n=new ve(this.p,this.A.size()),r=this.b;this.z(function(o){var i;try{i=Dt(t.T,t.U,r,t.A,e,t.O,n,t.W())}catch(e){return t.v=e,void t.P(ae.ERROR)}var a=t.U.makeRequest(i,o);t.m=a,a.getPromise().then(function(e){t.X(),t.m=null,t.B(e.current),e.finalized?(t.N=e.metadata,t.P(ae.SUCCESS)):t.L()},t.I)})},t.prototype.X=function(){262144*this.g<33554432&&(this.g*=2)},t.prototype.q=function(){var t=this;this.z(function(e){var n=Nt(t.U,t.T,t.O),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.P(ae.SUCCESS)},t.x)})},t.prototype.H=function(){var t=this;this.z(function(e){var n=It(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.B(t.A.size()),t.P(ae.SUCCESS)},t.I)})},t.prototype.B=function(t){var e=this.p;this.p=t,this.p!==e&&this.V()},t.prototype.P=function(t){if(this.k!==t)switch(t){case ae.CANCELING:case ae.PAUSING:this.k=t,null!==this.m&&this.m.cancel();break;case ae.RUNNING:var e=this.k===ae.PAUSED;this.k=t,e&&(this.V(),this.M());break;case ae.PAUSED:this.k=t,this.V();break;case ae.CANCELED:this.v=l(),this.k=t,this.V();break;case ae.ERROR:case ae.SUCCESS:this.k=t,this.V()}},t.prototype.L=function(){switch(this.k){case ae.PAUSING:this.P(ae.PAUSED);break;case ae.CANCELING:this.P(ae.CANCELED);break;case ae.RUNNING:this.M()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=S(this.k);return new me(this.p,this.A.size(),t,this.N,this,this.w)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(e){if(t!==ie.STATE_CHANGED)throw"Expected one of the event types: ["+ie.STATE_CHANGED+"]."}function i(t){try{return void c(t)}catch(t){}try{if(l(t),!(W(t.next)||W(t.error)||W(t.complete)))throw"";return}catch(t){throw u}}function a(t){function e(e,n,o){null!==t&&ct("on",t,arguments);var i=new be(e,n,r);return h.K(i),function(){h.Z(i)}}return e}function s(t){if(null===t)throw u;i(t)}void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var u="Expected a function or an Object with one of `next`, `error`, `complete` properties.",c=vt(!0).validator,l=_t(null,!0).validator;ct("on",[ht(o),_t(i,!0),vt(!0),vt(!0)],arguments);var h=this,p=[_t(s),vt(!0),vt(!0)];return W(e)||W(n)||W(r)?a(null)(e,n,r):a(p)},t.prototype.then=function(t,e){return this.D.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.K=function(t){this._.push(t),this.J(t)},t.prototype.Z=function(t){Et(this._,t)},t.prototype.V=function(){var t=this;this.Q(),Rt(this._).forEach(function(e){t.J(e)})},t.prototype.Q=function(){if(null!==this.y){var t=!0;switch(S(this.k)){case se.SUCCESS:Mt(this.y.bind(null,this.snapshot))();break;case se.CANCELED:case se.ERROR:Mt(this.R.bind(null,this.v))();break;default:t=!1}t&&(this.y=null,this.R=null)}},t.prototype.J=function(t){switch(S(this.k)){case se.RUNNING:case se.PAUSED:null!==t.next&&Mt(t.next.bind(t,this.snapshot))();break;case se.SUCCESS:null!==t.complete&&Mt(t.complete.bind(t))();break;case se.CANCELED:case se.ERROR:null!==t.error&&Mt(t.error.bind(t,this.v))();break;default:null!==t.error&&Mt(t.error.bind(t,this.v))()}},t.prototype.resume=function(){ct("resume",[],arguments);var t=this.k===ae.PAUSED||this.k===ae.PAUSING;return t&&this.P(ae.RUNNING),t},t.prototype.pause=function(){ct("pause",[],arguments);var t=this.k===ae.RUNNING;return t&&this.P(ae.PAUSING),t},t.prototype.cancel=function(){ct("cancel",[],arguments);var t=this.k===ae.RUNNING||this.k===ae.PAUSING;return t&&this.P(ae.CANCELING),t},t}(),ye=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof le?e:le.makeFromUrl(e)}return t.prototype.toString=function(){return ct("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return rt()},t.prototype.child=function(t){ct("child",[ht()],arguments);var e=Z(this.location.path,t),n=new le(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=K(this.location.path);if(null===t)return null;var e=new le(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new le(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return J(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),ct("put",[pt(),ft(!0)],arguments),this.Y("put"),new ge(this,this.authWrapper,this.location,this.mappings(),new de(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=ne.RAW),ct("putString",[ht(),ht(E,!0),ft(!0)],arguments),this.Y("putString");var r=w(e,t),o=L(n);return!M(o.contentType)&&M(r.contentType)&&(o.contentType=r.contentType),new ge(this,this.authWrapper,this.location,this.mappings(),new de(r.data,!0),o)},t.prototype.delete=function(){ct("delete",[],arguments),this.Y("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Ct(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){ct("getMetadata",[],arguments),this.Y("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Nt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){ct("updateMetadata",[ft()],arguments),this.Y("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=Ot(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return ct("getDownloadURL",[],arguments),this.Y("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(M(e))return e;throw _()})},t.prototype.Y=function(t){if(""===this.location.path)throw g(t)},t}(),Re=function(){function t(t){this.D=D(t)}return t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Ee=function(){function t(){this.$={},this.tt=$t}return t.prototype.addRequest=function(t){function e(){delete r.$[n]}var n=this.tt;this.tt++,this.$[n]=t;var r=this;t.getPromise().then(e,e)},t.prototype.clear=function(){I(this.$,function(t,e){e&&e.cancel(!0)}),this.$={}},t}(),we=function(){function t(e,n,r,o,i){if(this.et=null,this.nt=!1,this.rt=e,null!==this.rt){var a=this.rt.options;M(a)&&(this.et=t.ot(a))}this.it=n,this.at=r,this.st=i,this.ut=o,this.ct=Qt,this.lt=Yt,this.ht=new Ee}return t.ot=function(t){var e=t.storageBucket||null;return null==e?null:le.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.rt&&M(this.rt.INTERNAL)&&M(this.rt.INTERNAL.getToken)?this.rt.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):x(null)},t.prototype.bucket=function(){if(this.nt)throw m();return this.et},t.prototype.service=function(){return this.ut},t.prototype.makeStorageReference=function(t){return this.it(this,t)},t.prototype.makeRequest=function(t,e){if(this.nt)return new Re(m());var n=this.at(t,e,this.st);return this.ht.addRequest(n),n},t.prototype.deleteApp=function(){this.nt=!0,this.rt=null,this.ht.clear()},t.prototype.maxUploadRetryTime=function(){return this.lt},t.prototype.setMaxUploadRetryTime=function(t){this.lt=t},t.prototype.maxOperationRetryTime=function(){return this.ct},t.prototype.setMaxOperationRetryTime=function(t){this.ct=t},t}(),Ue=function(){function t(t,e,n,r,o,i,a,s,u,c,l){this.pt=null,this.ft=null,this.y=null,this.R=null,this.dt=!1,this._t=!1,this.vt=t,this.bt=e,this.mt=n,this.gt=r,this.yt=o.slice(),this.Rt=i.slice(),this.Et=a,this.wt=s,this.Ut=c,this.Tt=u,this.st=l;var h=this;this.D=P(function(t,e){h.y=t,h.R=e,h.M()})}return t.prototype.M=function(){function t(t,e){function r(t){var e=t.loaded,r=t.lengthComputable?t.total:-1;null!==n.Ut&&n.Ut(e,r)}if(e)return void t(!1,new Te(!1,null,!0));var o=n.st.createXhrIo();n.pt=o,null!==n.Ut&&o.addUploadProgressListener(r),o.send(n.vt,n.bt,n.gt,n.mt).then(function(e){null!==n.Ut&&e.removeUploadProgressListener(r),n.pt=null,e=e;var o=e.getErrorCode()===zt.NO_ERROR,i=e.getStatus();if(!o||n.At(i)){var a=e.getErrorCode()===zt.ABORT;return void t(!1,new Te(!1,null,a))}var s=yt(n.yt,i);t(!0,new Te(s,e))})}function e(t,e){var r=n.y,i=n.R,a=e.xhr;if(e.wasSuccessCode)try{var s=n.Et(a,a.getResponseText());W(s)?r(s):r()}catch(t){i(t)}else if(null!==a){var u=o();u.setServerResponseProp(a.getResponseText()),i(n.wt?n.wt(a,u):u)}else if(e.canceled){var u=n._t?m():l();i(u)}else{var u=c();i(u)}}var n=this;this.dt?e(!1,new Te(!1,null,!0)):this.ft=Wt(t,e,this.Tt)},t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){this.dt=!0,this._t=t||!1,null!==this.ft&&Bt(this.ft),null!==this.pt&&this.pt.abort()},t.prototype.At=function(t){var e=t>=500&&t<600,n=[408,429],r=yt(n,t),o=yt(this.Rt,t);return e||r||o},t}(),Te=function(){function t(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}return t}(),Ae=function(){function t(t,e,n){function r(t,e){return new ye(t,e)}if(this.et=null,this.U=new we(t,r,qt,this,e),this.rt=t,null!=n)this.et=le.makeFromBucketSpec(n);else{var o=this.U.bucket();null!=o&&(this.et=new le(o,""))}this.Nt=new Ne(this)}return t.prototype.ref=function(t){function e(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."}if(ct("ref",[ht(e,!0)],arguments),null==this.et)throw Error("No Storage Bucket defined in Firebase Options.");var n=new ye(this.U,this.et);return null!=t?n.child(t):n},t.prototype.refFromURL=function(t){function e(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{le.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}}return ct("refFromURL",[ht(e,!1)],arguments),new ye(this.U,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.U.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){ct("setMaxUploadRetryTime",[dt()],arguments),this.U.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.U.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){ct("setMaxOperationRetryTime",[dt()],arguments),this.U.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.rt},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.Nt},enumerable:!0,configurable:!0}),t}(),Ne=function(){function t(t){this.ut=t}return t.prototype.delete=function(){return this.ut.U.deleteApp(),x(void 0)},t}();e.registerStorage=Ht;var Oe="storage";Ht(Xt.default)}},[118])}catch(t){throw Error("Cannot instantiate firebase-storage.js - be sure to load firebase-app.js first.")} +try{webpackJsonpFirebase([2],{122:function(t,e,n){n(123)},123:function(t,e,n){"use strict";function r(t){return"storage/"+t}function o(){return new te(ee.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function i(t){return new te(ee.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function a(t){return new te(ee.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function s(){return new te(ee.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}function u(t){return new te(ee.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function c(){return new te(ee.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function l(){return new te(ee.CANCELED,"User canceled the upload/download.")}function h(t){return new te(ee.INVALID_URL,"Invalid URL '"+t+"'.")}function p(t){return new te(ee.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function f(){return new te(ee.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function d(){return new te(ee.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function _(){return new te(ee.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function v(t,e,n){return new te(ee.INVALID_ARGUMENT,"Invalid argument in `"+e+"` at index "+t+": "+n)}function b(t,e,n,r){var o,i;return t===e?(o=t,i=1===t?"argument":"arguments"):(o="between "+t+" and "+e,i="arguments"),new te(ee.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+n+"`: Expected "+o+" "+i+", received "+r+".")}function m(){return new te(ee.APP_DELETED,"The Firebase app was deleted.")}function g(t){return new te(ee.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function y(t,e){return new te(ee.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function R(t){throw new te(ee.INTERNAL_ERROR,"Internal error: "+t)}function E(t){switch(t){case ne.RAW:case ne.BASE64:case ne.BASE64URL:case ne.DATA_URL:return;default:throw"Expected one of the event types: ["+ne.RAW+", "+ne.BASE64+", "+ne.BASE64URL+", "+ne.DATA_URL+"]."}}function w(t,e){switch(t){case ne.RAW:return new re(U(e));case ne.BASE64:case ne.BASE64URL:return new re(A(t,e));case ne.DATA_URL:return new re(N(e),O(e))}throw o()}function U(t){for(var e=[],n=0;n>6,128|63&r);else if(55296==(64512&r)){var o=n>18,128|r>>12&63,128|r>>6&63,128|63&r)}else e.push(239,191,189)}else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function T(t){var e;try{e=decodeURIComponent(t)}catch(t){throw y(ne.DATA_URL,"Malformed data URL.")}return U(e)}function A(t,e){switch(t){case ne.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r){var o=n?"-":"_";throw y(t,"Invalid character '"+o+"' found: is it base64url encoded?")}break;case ne.BASE64URL:var i=-1!==e.indexOf("+"),a=-1!==e.indexOf("/");if(i||a){var o=i?"+":"/";throw y(t,"Invalid character '"+o+"' found: is it base64 encoded?")}e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw y(t,"Invalid character found")}for(var u=new Uint8Array(s.length),c=0;c=e.length)&&t.substring(t.length-e.length)===e}function S(t){switch(t){case ae.RUNNING:case ae.PAUSING:case ae.CANCELING:return se.RUNNING;case ae.PAUSED:return se.PAUSED;case ae.SUCCESS:return se.SUCCESS;case ae.CANCELED:return se.CANCELED;case ae.ERROR:default:return se.ERROR}}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function I(t,e){for(var n in t)k(t,n)&&e(n,t[n])}function L(t){if(null==t)return{};var e={};return I(t,function(t,n){e[t]=n}),e}function P(t){return new Promise(t)}function x(t){return Promise.resolve(t)}function D(t){return Promise.reject(t)}function M(t){return null!=t}function W(t){return void 0!==t}function B(t){return"function"==typeof t}function G(t){return"object"==typeof t}function j(t){return G(t)&&null!==t}function q(t){return G(t)&&!Array.isArray(t)}function F(t){return"string"==typeof t||t instanceof String}function H(t){return"number"==typeof t||t instanceof Number}function z(t){return X()&&t instanceof Blob}function X(){return"undefined"!=typeof Blob}function V(t){var e;try{e=JSON.parse(t)}catch(t){return null}return q(e)?e:null}function K(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}function Z(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}function J(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Q(t){return Vt+Zt+t}function Y(t){return Kt+Zt+t}function $(t){return Vt+Jt+t}function tt(t){var e=encodeURIComponent,n="?";return I(t,function(t,r){var o=e(t)+"="+e(r);n=n+o+"&"}),n=n.slice(0,-1)}function et(t,e){return e}function nt(t){return!F(t)||t.length<2?t:(t=t,J(t))}function rt(){function t(t,e){return nt(e)}function e(t,e){return M(e)?+e:e}function n(t,e){if(!(F(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,o=t.fullPath;return Y("/b/"+n(r)+"/o/"+n(o))+tt({alt:"media",token:e})})}if(pe)return pe;var r=[];r.push(new he("bucket")),r.push(new he("generation")),r.push(new he("metageneration")),r.push(new he("name","fullPath",!0));var o=new he("name");o.xform=t,r.push(o);var i=new he("size");return i.xform=e,r.push(i),r.push(new he("timeCreated")),r.push(new he("updated")),r.push(new he("md5Hash",null,!0)),r.push(new he("cacheControl",null,!0)),r.push(new he("contentDisposition",null,!0)),r.push(new he("contentEncoding",null,!0)),r.push(new he("contentLanguage",null,!0)),r.push(new he("contentType",null,!0)),r.push(new he("metadata","customMetadata",!0)),r.push(new he("downloadTokens","downloadURLs",!1,n)),pe=r}function ot(t,e){function n(){var n=t.bucket,r=t.fullPath,o=new le(n,r);return e.makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function it(t,e,n){var r={};r.type="file";for(var o=n.length,i=0;i=0))throw"Expected a number 0 or greater."}return new fe(t)}function _t(t,e){function n(e){if(!(null===e||M(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)}return new fe(n,e)}function vt(t){function e(t){if(null!==t&&!B(t))throw"Expected a Function."}return new fe(e,t)}function bt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function mt(){for(var t=[],e=0;e0&&(h=Math.min(h,o));var p=c.current,_=p+h,v=h===l?"upload, finalize":"upload",b={"X-Goog-Upload-Command":v,"X-Goog-Upload-Offset":c.current},m=r.slice(p,_);if(null===m)throw f();var g=e.maxUploadRetryTime(),y=new _e(n,"POST",u,g);return y.headers=b,y.body=m.uploadData(),y.progressCallback=s||null,y.errorHandler=Tt(t),y}function Mt(t){return function(){for(var e=[],n=0;n0&&(t.Authorization="Firebase "+e)}function jt(t){var e=void 0!==Xt.default?Xt.default.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}function qt(t,e,n){var r=tt(t.urlParams),o=t.url+r,i=L(t.headers);return Gt(i,e),jt(i),new Ue(o,t.method,i,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}function Ft(t,e,n){return new Ae(t,new ce,n)}function Ht(t){var e={TaskState:se,TaskEvent:ie,StringFormat:ne,Storage:Ae,Reference:ye};t.INTERNAL.registerService(Oe,Ft,e,void 0,!0)}Object.defineProperty(e,"__esModule",{value:!0});var zt,Xt=n(7),Vt="https://firebasestorage.googleapis.com",Kt="https://firebasestorage.googleapis.com",Zt="/v0",Jt="/v0",Qt=12e4,Yt=6e4,$t=-9007199254740991,te=function(){function t(t,e){this.t=r(t),this.e="Firebase Storage: "+e,this.n=null,this.r="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return r(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.n},t.prototype.setServerResponseProp=function(t){this.n=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.r},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.n},enumerable:!0,configurable:!0}),t}(),ee={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"},ne={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},re=function(){function t(t,e){this.data=t,this.contentType=e||null}return t}(),oe=function(){function t(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw y(ne.DATA_URL,"Must be formatted 'data:[][;base64],");var n=e[1]||null;null!=n&&(this.base64=C(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=t.substring(t.indexOf(",")+1)}return t}(),ie={STATE_CHANGED:"state_changed"},ae={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},se={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(zt||(zt={}));var ue=function(){function t(){var t=this;this.o=!1,this.i=new XMLHttpRequest,this.a=zt.NO_ERROR,this.s=P(function(e,n){t.i.addEventListener("abort",function(n){t.a=zt.ABORT,e(t)}),t.i.addEventListener("error",function(n){t.a=zt.NETWORK_ERROR,e(t)}),t.i.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var o=this;if(this.o)throw R("cannot .send() more than once");return this.o=!0,this.i.open(e,t,!0),M(r)&&I(r,function(t,e){o.i.setRequestHeader(t,""+e)}),M(n)?this.i.send(n):this.i.send(),this.s},t.prototype.getErrorCode=function(){if(!this.o)throw R("cannot .getErrorCode() before sending");return this.a},t.prototype.getStatus=function(){if(!this.o)throw R("cannot .getStatus() before sending");try{return this.i.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.o)throw R("cannot .getResponseText() before sending");return this.i.responseText},t.prototype.abort=function(){this.i.abort()},t.prototype.getResponseHeader=function(t){return this.i.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.removeEventListener("progress",t)},t}(),ce=function(){function t(){}return t.prototype.createXhrIo=function(){return new ue},t}(),le=function(){function t(t,e){this.bucket=t,this.u=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.u},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw p(e)},t.makeFromUrl=function(e){function n(t){"/"===t.path.charAt(t.path.length-1)&&(t.u=t.u.slice(0,-1))}function r(t){t.u=decodeURIComponent(t.path)}for(var o=null,i=RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),a={bucket:1,path:3},s=RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),u={bucket:1,path:3},c=[{regex:i,indices:a,postModify:n},{regex:s,indices:u,postModify:r}],l=0;l262144},t.prototype.M=function(){this.k===ae.RUNNING&&null===this.m&&(this.C?null===this.b?this.G():this.f?this.j():this.d?this.q():this.F():this.H())},t.prototype.z=function(t){var e=this;this.U.getAuthToken().then(function(n){switch(e.k){case ae.RUNNING:t(n);break;case ae.CANCELING:e.P(ae.CANCELED);break;case ae.PAUSING:e.P(ae.PAUSED)}})},t.prototype.G=function(){var t=this;this.z(function(e){var n=Pt(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.b=e,t.f=!1,t.L()},t.I)})},t.prototype.j=function(){var t=this,e=this.b;this.z(function(n){var r=xt(t.U,t.T,e,t.A),o=t.U.makeRequest(r,n);t.m=o,o.getPromise().then(function(e){e=e,t.m=null,t.B(e.current),t.f=!1,e.finalized&&(t.d=!0),t.L()},t.I)})},t.prototype.F=function(){var t=this,e=262144*this.g,n=new ve(this.p,this.A.size()),r=this.b;this.z(function(o){var i;try{i=Dt(t.T,t.U,r,t.A,e,t.O,n,t.W())}catch(e){return t.v=e,void t.P(ae.ERROR)}var a=t.U.makeRequest(i,o);t.m=a,a.getPromise().then(function(e){t.X(),t.m=null,t.B(e.current),e.finalized?(t.N=e.metadata,t.P(ae.SUCCESS)):t.L()},t.I)})},t.prototype.X=function(){262144*this.g<33554432&&(this.g*=2)},t.prototype.q=function(){var t=this;this.z(function(e){var n=Nt(t.U,t.T,t.O),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.P(ae.SUCCESS)},t.x)})},t.prototype.H=function(){var t=this;this.z(function(e){var n=It(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.B(t.A.size()),t.P(ae.SUCCESS)},t.I)})},t.prototype.B=function(t){var e=this.p;this.p=t,this.p!==e&&this.V()},t.prototype.P=function(t){if(this.k!==t)switch(t){case ae.CANCELING:case ae.PAUSING:this.k=t,null!==this.m&&this.m.cancel();break;case ae.RUNNING:var e=this.k===ae.PAUSED;this.k=t,e&&(this.V(),this.M());break;case ae.PAUSED:this.k=t,this.V();break;case ae.CANCELED:this.v=l(),this.k=t,this.V();break;case ae.ERROR:case ae.SUCCESS:this.k=t,this.V()}},t.prototype.L=function(){switch(this.k){case ae.PAUSING:this.P(ae.PAUSED);break;case ae.CANCELING:this.P(ae.CANCELED);break;case ae.RUNNING:this.M()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=S(this.k);return new me(this.p,this.A.size(),t,this.N,this,this.w)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(e){if(t!==ie.STATE_CHANGED)throw"Expected one of the event types: ["+ie.STATE_CHANGED+"]."}function i(t){try{return void c(t)}catch(t){}try{if(l(t),!(W(t.next)||W(t.error)||W(t.complete)))throw"";return}catch(t){throw u}}function a(t){function e(e,n,o){null!==t&&ct("on",t,arguments);var i=new be(e,n,r);return h.K(i),function(){h.Z(i)}}return e}function s(t){if(null===t)throw u;i(t)}void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var u="Expected a function or an Object with one of `next`, `error`, `complete` properties.",c=vt(!0).validator,l=_t(null,!0).validator;ct("on",[ht(o),_t(i,!0),vt(!0),vt(!0)],arguments);var h=this,p=[_t(s),vt(!0),vt(!0)];return W(e)||W(n)||W(r)?a(null)(e,n,r):a(p)},t.prototype.then=function(t,e){return this.D.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.K=function(t){this._.push(t),this.J(t)},t.prototype.Z=function(t){Et(this._,t)},t.prototype.V=function(){var t=this;this.Q(),Rt(this._).forEach(function(e){t.J(e)})},t.prototype.Q=function(){if(null!==this.y){var t=!0;switch(S(this.k)){case se.SUCCESS:Mt(this.y.bind(null,this.snapshot))();break;case se.CANCELED:case se.ERROR:Mt(this.R.bind(null,this.v))();break;default:t=!1}t&&(this.y=null,this.R=null)}},t.prototype.J=function(t){switch(S(this.k)){case se.RUNNING:case se.PAUSED:null!==t.next&&Mt(t.next.bind(t,this.snapshot))();break;case se.SUCCESS:null!==t.complete&&Mt(t.complete.bind(t))();break;case se.CANCELED:case se.ERROR:null!==t.error&&Mt(t.error.bind(t,this.v))();break;default:null!==t.error&&Mt(t.error.bind(t,this.v))()}},t.prototype.resume=function(){ct("resume",[],arguments);var t=this.k===ae.PAUSED||this.k===ae.PAUSING;return t&&this.P(ae.RUNNING),t},t.prototype.pause=function(){ct("pause",[],arguments);var t=this.k===ae.RUNNING;return t&&this.P(ae.PAUSING),t},t.prototype.cancel=function(){ct("cancel",[],arguments);var t=this.k===ae.RUNNING||this.k===ae.PAUSING;return t&&this.P(ae.CANCELING),t},t}(),ye=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof le?e:le.makeFromUrl(e)}return t.prototype.toString=function(){return ct("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return rt()},t.prototype.child=function(t){ct("child",[ht()],arguments);var e=Z(this.location.path,t),n=new le(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=K(this.location.path);if(null===t)return null;var e=new le(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new le(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return J(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),ct("put",[pt(),ft(!0)],arguments),this.Y("put"),new ge(this,this.authWrapper,this.location,this.mappings(),new de(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=ne.RAW),ct("putString",[ht(),ht(E,!0),ft(!0)],arguments),this.Y("putString");var r=w(e,t),o=L(n);return!M(o.contentType)&&M(r.contentType)&&(o.contentType=r.contentType),new ge(this,this.authWrapper,this.location,this.mappings(),new de(r.data,!0),o)},t.prototype.delete=function(){ct("delete",[],arguments),this.Y("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Ct(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){ct("getMetadata",[],arguments),this.Y("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Nt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){ct("updateMetadata",[ft()],arguments),this.Y("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=Ot(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return ct("getDownloadURL",[],arguments),this.Y("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(M(e))return e;throw _()})},t.prototype.Y=function(t){if(""===this.location.path)throw g(t)},t}(),Re=function(){function t(t){this.D=D(t)}return t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Ee=function(){function t(){this.$={},this.tt=$t}return t.prototype.addRequest=function(t){function e(){delete r.$[n]}var n=this.tt;this.tt++,this.$[n]=t;var r=this;t.getPromise().then(e,e)},t.prototype.clear=function(){I(this.$,function(t,e){e&&e.cancel(!0)}),this.$={}},t}(),we=function(){function t(e,n,r,o,i){if(this.et=null,this.nt=!1,this.rt=e,null!==this.rt){var a=this.rt.options;M(a)&&(this.et=t.ot(a))}this.it=n,this.at=r,this.st=i,this.ut=o,this.ct=Qt,this.lt=Yt,this.ht=new Ee}return t.ot=function(t){var e=t.storageBucket||null;return null==e?null:le.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.rt&&M(this.rt.INTERNAL)&&M(this.rt.INTERNAL.getToken)?this.rt.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):x(null)},t.prototype.bucket=function(){if(this.nt)throw m();return this.et},t.prototype.service=function(){return this.ut},t.prototype.makeStorageReference=function(t){return this.it(this,t)},t.prototype.makeRequest=function(t,e){if(this.nt)return new Re(m());var n=this.at(t,e,this.st);return this.ht.addRequest(n),n},t.prototype.deleteApp=function(){this.nt=!0,this.rt=null,this.ht.clear()},t.prototype.maxUploadRetryTime=function(){return this.lt},t.prototype.setMaxUploadRetryTime=function(t){this.lt=t},t.prototype.maxOperationRetryTime=function(){return this.ct},t.prototype.setMaxOperationRetryTime=function(t){this.ct=t},t}(),Ue=function(){function t(t,e,n,r,o,i,a,s,u,c,l){this.pt=null,this.ft=null,this.y=null,this.R=null,this.dt=!1,this._t=!1,this.vt=t,this.bt=e,this.mt=n,this.gt=r,this.yt=o.slice(),this.Rt=i.slice(),this.Et=a,this.wt=s,this.Ut=c,this.Tt=u,this.st=l;var h=this;this.D=P(function(t,e){h.y=t,h.R=e,h.M()})}return t.prototype.M=function(){function t(t,e){function r(t){var e=t.loaded,r=t.lengthComputable?t.total:-1;null!==n.Ut&&n.Ut(e,r)}if(e)return void t(!1,new Te(!1,null,!0));var o=n.st.createXhrIo();n.pt=o,null!==n.Ut&&o.addUploadProgressListener(r),o.send(n.vt,n.bt,n.gt,n.mt).then(function(e){null!==n.Ut&&e.removeUploadProgressListener(r),n.pt=null,e=e;var o=e.getErrorCode()===zt.NO_ERROR,i=e.getStatus();if(!o||n.At(i)){var a=e.getErrorCode()===zt.ABORT;return void t(!1,new Te(!1,null,a))}var s=yt(n.yt,i);t(!0,new Te(s,e))})}function e(t,e){var r=n.y,i=n.R,a=e.xhr;if(e.wasSuccessCode)try{var s=n.Et(a,a.getResponseText());W(s)?r(s):r()}catch(t){i(t)}else if(null!==a){var u=o();u.setServerResponseProp(a.getResponseText()),i(n.wt?n.wt(a,u):u)}else if(e.canceled){var u=n._t?m():l();i(u)}else{var u=c();i(u)}}var n=this;this.dt?e(!1,new Te(!1,null,!0)):this.ft=Wt(t,e,this.Tt)},t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){this.dt=!0,this._t=t||!1,null!==this.ft&&Bt(this.ft),null!==this.pt&&this.pt.abort()},t.prototype.At=function(t){var e=t>=500&&t<600,n=[408,429],r=yt(n,t),o=yt(this.Rt,t);return e||r||o},t}(),Te=function(){function t(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}return t}(),Ae=function(){function t(t,e,n){function r(t,e){return new ye(t,e)}if(this.et=null,this.U=new we(t,r,qt,this,e),this.rt=t,null!=n)this.et=le.makeFromBucketSpec(n);else{var o=this.U.bucket();null!=o&&(this.et=new le(o,""))}this.Nt=new Ne(this)}return t.prototype.ref=function(t){function e(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."}if(ct("ref",[ht(e,!0)],arguments),null==this.et)throw Error("No Storage Bucket defined in Firebase Options.");var n=new ye(this.U,this.et);return null!=t?n.child(t):n},t.prototype.refFromURL=function(t){function e(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{le.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}}return ct("refFromURL",[ht(e,!1)],arguments),new ye(this.U,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.U.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){ct("setMaxUploadRetryTime",[dt()],arguments),this.U.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.U.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){ct("setMaxOperationRetryTime",[dt()],arguments),this.U.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.rt},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.Nt},enumerable:!0,configurable:!0}),t}(),Ne=function(){function t(t){this.ut=t}return t.prototype.delete=function(){return this.ut.U.deleteApp(),x(void 0)},t}();e.registerStorage=Ht;var Oe="storage";Ht(Xt.default)}},[122])}catch(t){throw Error("Cannot instantiate firebase-storage.js - be sure to load firebase-app.js first.")} //# sourceMappingURL=firebase.js.map diff --git a/lib/firebase/firebase.js.map b/lib/firebase/firebase.js.map index 5ad70ab1..d445c034 100644 --- a/lib/firebase/firebase.js.map +++ b/lib/firebase/firebase.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///firebase-app.js","webpack:/webpack/bootstrap 6be335cb5a7765bfd560","webpack:///util/dist/cjs/index.js","webpack:///app/dist/esm/src/firebaseApp.js","webpack:///app/dist/esm/index.js","webpack:///(webpack)/buildin/global.js","webpack:///util/dist/cjs/src/constants.js","webpack:///Users/jshcrowthe/Repos/firebase-js-sdk/node_modules/process/browser.js","webpack:///util/dist/cjs/src/assert.js","webpack:///util/dist/cjs/src/crypt.js","webpack:///util/dist/cjs/src/json.js","webpack:///util/dist/cjs/src/obj.js","webpack:///app/index.js","webpack:///polyfill/dist/esm/index.js","webpack:///polyfill/dist/esm/src/polyfills/promise.js","webpack:///Users/jshcrowthe/Repos/firebase-js-sdk/node_modules/promise-polyfill/promise.js","webpack:///Users/jshcrowthe/Repos/firebase-js-sdk/node_modules/node-libs-browser/node_modules/timers-browserify/main.js","webpack:///Users/jshcrowthe/Repos/firebase-js-sdk/node_modules/setimmediate/setImmediate.js","webpack:///polyfill/dist/esm/src/shims/find.js","webpack:///polyfill/dist/esm/src/shims/findIndex.js","webpack:///util/dist/cjs/src/deepCopy.js","webpack:///util/dist/cjs/src/deferred.js","webpack:///util/dist/cjs/src/environment.js","webpack:///util/dist/cjs/src/errors.js","webpack:///util/dist/cjs/src/jwt.js","webpack:///util/dist/cjs/src/query.js","webpack:///util/dist/cjs/src/sha1.js","webpack:///util/dist/cjs/src/hash.js","webpack:///util/dist/cjs/src/subscribe.js","webpack:///util/dist/cjs/src/validation.js","webpack:///util/dist/cjs/src/utf8.js","webpack:///firebase-auth.js","webpack:///auth/index.js","webpack:///auth/dist/auth.js","webpack:///firebase-database.js","webpack:///database/dist/cjs/src/core/util/util.js","webpack:///database/dist/cjs/src/core/util/Path.js","webpack:///database/dist/cjs/src/core/snap/indexes/PriorityIndex.js","webpack:///database/dist/cjs/src/core/snap/ChildrenNode.js","webpack:///database/dist/cjs/src/core/snap/Node.js","webpack:///database/dist/cjs/src/core/util/validation.js","webpack:///database/dist/cjs/src/core/operation/Operation.js","webpack:///database/dist/cjs/src/core/view/Change.js","webpack:///database/dist/cjs/src/core/snap/indexes/KeyIndex.js","webpack:///database/dist/cjs/src/core/snap/nodeFromJSON.js","webpack:///database/dist/cjs/src/core/storage/storage.js","webpack:///database/dist/cjs/src/realtime/Constants.js","webpack:///database/dist/cjs/src/core/snap/indexes/Index.js","webpack:///database/dist/cjs/src/core/snap/LeafNode.js","webpack:///database/dist/cjs/src/core/util/SortedMap.js","webpack:///database/dist/cjs/src/core/Repo.js","webpack:///database/dist/cjs/src/core/view/CacheNode.js","webpack:///database/dist/cjs/src/api/Reference.js","webpack:///database/dist/cjs/src/api/DataSnapshot.js","webpack:///database/dist/cjs/src/core/util/ImmutableTree.js","webpack:///database/dist/cjs/src/core/view/filter/IndexedFilter.js","webpack:///database/dist/cjs/src/core/stats/StatsManager.js","webpack:///database/dist/cjs/src/core/RepoManager.js","webpack:///database/dist/cjs/src/api/Database.js","webpack:///database/dist/cjs/src/core/util/libs/parser.js","webpack:///database/dist/cjs/src/core/RepoInfo.js","webpack:///database/dist/cjs/src/api/onDisconnect.js","webpack:///database/dist/cjs/src/api/Query.js","webpack:///database/dist/cjs/src/core/snap/snap.js","webpack:///database/dist/cjs/src/core/snap/indexes/ValueIndex.js","webpack:///database/dist/cjs/src/core/snap/IndexMap.js","webpack:///database/dist/cjs/src/core/snap/childSet.js","webpack:///database/dist/cjs/src/core/snap/comparators.js","webpack:///database/dist/cjs/src/core/snap/indexes/PathIndex.js","webpack:///database/dist/cjs/src/core/util/ServerValues.js","webpack:///database/dist/cjs/src/core/SparseSnapshotTree.js","webpack:///database/dist/cjs/src/core/util/CountedSet.js","webpack:///database/dist/cjs/src/core/operation/Overwrite.js","webpack:///database/dist/cjs/src/core/SyncPoint.js","webpack:///database/dist/cjs/src/core/view/ViewCache.js","webpack:///database/dist/cjs/src/core/stats/StatsListener.js","webpack:///database/dist/cjs/src/core/PersistentConnection.js","webpack:///database/dist/cjs/src/core/util/EventEmitter.js","webpack:///database/dist/cjs/src/realtime/Connection.js","webpack:///database/dist/cjs/src/realtime/BrowserPollConnection.js","webpack:///database/dist/cjs/src/realtime/WebSocketConnection.js","webpack:///database/dist/cjs/src/core/ServerActions.js","webpack:///database/dist/cjs/src/core/view/filter/RangedFilter.js","webpack:///database/index.js","webpack:///database/dist/cjs/index.js","webpack:///database/dist/cjs/src/core/storage/DOMStorageWrapper.js","webpack:///database/dist/cjs/src/core/storage/MemoryStorage.js","webpack:///database/dist/cjs/src/api/TransactionResult.js","webpack:///database/dist/cjs/src/core/util/NextPushId.js","webpack:///database/dist/cjs/src/core/view/EventRegistration.js","webpack:///database/dist/cjs/src/core/view/Event.js","webpack:///database/dist/cjs/src/core/SyncTree.js","webpack:///database/dist/cjs/src/core/operation/AckUserWrite.js","webpack:///database/dist/cjs/src/core/operation/ListenComplete.js","webpack:///database/dist/cjs/src/core/operation/Merge.js","webpack:///database/dist/cjs/src/core/view/View.js","webpack:///database/dist/cjs/src/core/view/ViewProcessor.js","webpack:///database/dist/cjs/src/core/view/ChildChangeAccumulator.js","webpack:///database/dist/cjs/src/core/view/CompleteChildSource.js","webpack:///database/dist/cjs/src/core/view/EventGenerator.js","webpack:///database/dist/cjs/src/core/WriteTree.js","webpack:///database/dist/cjs/src/core/CompoundWrite.js","webpack:///database/dist/cjs/src/core/SnapshotHolder.js","webpack:///database/dist/cjs/src/core/AuthTokenProvider.js","webpack:///database/dist/cjs/src/core/stats/StatsCollection.js","webpack:///database/dist/cjs/src/core/stats/StatsReporter.js","webpack:///database/dist/cjs/src/core/view/EventQueue.js","webpack:///database/dist/cjs/src/core/util/VisibilityMonitor.js","webpack:///database/dist/cjs/src/core/util/OnlineMonitor.js","webpack:///database/dist/cjs/src/realtime/TransportManager.js","webpack:///database/dist/cjs/src/realtime/polling/PacketReceiver.js","webpack:///database/dist/cjs/src/core/ReadonlyRestClient.js","webpack:///database/dist/cjs/src/core/view/QueryParams.js","webpack:///database/dist/cjs/src/core/view/filter/LimitedFilter.js","webpack:///database/dist/cjs/src/core/Repo_transaction.js","webpack:///database/dist/cjs/src/core/util/Tree.js","webpack:///database/dist/cjs/src/api/internal.js","webpack:///database/dist/cjs/src/api/test_access.js","webpack:///firebase-messaging.js","webpack:///messaging/index.js","webpack:///messaging/dist/esm/src/helpers/array-buffer-to-base64.js","webpack:///messaging/dist/esm/index.js","webpack:///messaging/dist/esm/src/models/errors.js","webpack:///messaging/dist/esm/src/models/fcm-details.js","webpack:///messaging/dist/esm/src/models/token-manager.js","webpack:///messaging/dist/esm/src/controllers/controller-interface.js","webpack:///messaging/dist/esm/src/models/worker-page-message.js","webpack:///messaging/dist/esm/src/models/default-sw.js","webpack:///messaging/dist/esm/src/controllers/window-controller.js","webpack:///messaging/dist/esm/src/controllers/sw-controller.js","webpack:///firebase-storage.js","webpack:///storage/index.js","webpack:///storage/dist/esm/src/implementation/error.js","webpack:///storage/dist/esm/src/implementation/string.js","webpack:///storage/dist/esm/src/implementation/taskenums.js","webpack:///storage/dist/esm/src/implementation/object.js","webpack:///storage/dist/esm/src/implementation/promise_external.js","webpack:///storage/dist/esm/src/implementation/type.js","webpack:///storage/dist/esm/src/implementation/json.js","webpack:///storage/dist/esm/src/implementation/path.js","webpack:///storage/dist/esm/src/implementation/url.js","webpack:///storage/dist/esm/src/implementation/metadata.js","webpack:///storage/dist/esm/src/implementation/args.js","webpack:///storage/dist/esm/src/implementation/fs.js","webpack:///storage/dist/esm/src/implementation/array.js","webpack:///storage/dist/esm/src/implementation/requests.js","webpack:///storage/dist/esm/src/implementation/async.js","webpack:///storage/dist/esm/src/implementation/backoff.js","webpack:///storage/dist/esm/src/implementation/request.js","webpack:///storage/dist/esm/index.js","webpack:///storage/dist/esm/src/implementation/xhrio.js","webpack:///storage/dist/esm/src/implementation/constants.js","webpack:///storage/dist/esm/src/implementation/xhrio_network.js","webpack:///storage/dist/esm/src/implementation/xhriopool.js","webpack:///storage/dist/esm/src/implementation/location.js","webpack:///storage/dist/esm/src/implementation/blob.js","webpack:///storage/dist/esm/src/implementation/requestinfo.js","webpack:///storage/dist/esm/src/implementation/observer.js","webpack:///storage/dist/esm/src/tasksnapshot.js","webpack:///storage/dist/esm/src/task.js","webpack:///storage/dist/esm/src/reference.js","webpack:///storage/dist/esm/src/implementation/failrequest.js","webpack:///storage/dist/esm/src/implementation/requestmap.js","webpack:///storage/dist/esm/src/implementation/authwrapper.js","webpack:///storage/dist/esm/src/service.js"],"names":["firebase","window","self","modules","__webpack_require__","moduleId","installedModules","exports","module","i","l","call","parentJsonpFunction","chunkIds","moreModules","executeModules","chunkId","result","resolves","length","installedChunks","push","Object","prototype","hasOwnProperty","shift","s","5","e","onScriptComplete","script","onerror","onload","clearTimeout","timeout","chunk","Error","undefined","installedChunkData","Promise","resolve","promise","reject","head","document","getElementsByTagName","createElement","type","charset","async","nc","setAttribute","src","p","setTimeout","appendChild","m","c","d","name","getter","o","defineProperty","configurable","enumerable","get","n","__esModule","object","property","oe","err","console","error","__export","value","__webpack_exports__","createFirebaseNamespace","removeApp","callAppHooks","apps_","app","DEFAULT_ENTRY_NAME","contains","initializeApp","options","firebaseApp_FirebaseAppImpl","namespace","getApps","keys","map","registerService","createService","serviceProperties","appHook","allowMultipleInstances","factories","appHooks","forEach","serviceNamespace","appArg","cjs","args","_i","arguments","this","_getService","bind","apply","extendNamespace","props","eventName","serviceName","factoryName","useAsService","useService","apps","SDK_VERSION","INTERNAL","createSubscribe","ErrorFactory","deepExtend","code","appErrors","create","obj","key","tokenListeners","FirebaseAppImpl","firebase_","isDeleted_","services_","name_","options_","getUid","getToken","addAuthTokenListener","callback","removeAuthTokenListener","filter","listener","checkDestroyed_","delete","_this","then","services","serviceKey","instanceKey","all","service","instanceIdentifier","instanceSpecifier","extendApp","log","errors","no-app","bad-app-name","duplicate-app","app-deleted","duplicate-service","sa-not-supported","invalid-app-argument","g","Function","eval","CONSTANTS","NODE_CLIENT","NODE_ADMIN","defaultSetTimout","defaultClearTimeout","runTimeout","fun","cachedSetTimeout","runClearTimeout","marker","cachedClearTimeout","cleanUpNextTick","draining","currentQueue","queue","concat","queueIndex","drainQueue","len","run","Item","array","noop","process","nextTick","Array","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","constants_1","assert","assertion","message","assertionError","stringToByteArray","str","output","charCodeAt","byteArrayToString","bytes","String","fromCharCode","slice","base64","y","b","_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","opt_webSafe","isArray","init_","byteToCharMap","byteToCharMapWebSafe_","byteToCharMap_","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","join","encodeString","btoa","decodeString","decodeStringToByteArray","charToByteMap","charToByteMapWebSafe_","charToByteMap_","charAt","haveByte4","byte4","O","base64Encode","utf8Bytes","base64Decode","jsonEval","JSON","parse","stringify","data","safeGet","fn","extend","objTo","objFrom","clone","isNonNullObject","isEmpty","getCount","rv","f","opt_obj","res","findKey","opt_this","findValue","getAnyKey","getValues","every","default","__WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__","__WEBPACK_IMPORTED_MODULE_1__src_shims_find__","__WEBPACK_IMPORTED_MODULE_2__src_shims_findIndex__","global","__global","setImmediate","root","thisArg","TypeError","_state","_handled","_value","_deferreds","doResolve","handle","deferred","_immediateFn","cb","onFulfilled","onRejected","ret","newValue","finale","_unhandledRejectionFn","Handler","done","reason","ex","setTimeoutFunc","prom","arr","val","remaining","constructor","race","values","warn","_setImmediateFn","_setUnhandledRejectionFn","Timeout","id","clearFn","_id","_clearFn","setInterval","clearInterval","close","unref","ref","enroll","item","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","clearImmediate","task","tasksByHandle","nextHandle","registerImmediate","runIfPresent","currentlyRunningATask","doc","attachTo","getPrototypeOf","toString","postMessage","importScripts","postMessageIsAsynchronous","oldOnMessage","onmessage","messagePrefix","Math","random","onGlobalMessage","event","source","indexOf","addEventListener","attachEvent","MessageChannel","channel","port1","port2","html","documentElement","onreadystatechange","removeChild","find","predicate","k","kValue","findIndex","deepCopy","target","Date","dateValue","getTime","prop","patchProperty","Deferred","wrapCallback","catch","getUA","navigator","isMobileCordova","test","isReactNative","isNodeSdk","patchCapture","captureFake","captureStackTrace","ERROR_NAME","FirebaseError","err_1","stack","pattern","template","fullCode","replace","match","crypt_1","json_1","decode","token","header","claims","signature","parts","split","isValidTimestamp","validSince","validUntil","now","floor","issuedAtTime","isValidFormat","decoded","isAdmin","obj_1","querystring","querystringParams","params","arrayVal","encodeURIComponent","querystringDecode","__extends","extendStatics","setPrototypeOf","__proto__","__","hash_1","Sha1","_super","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","opt_offset","W","t","a","update","opt_length","lengthMinusBlock","inbuf","digest","totalBits","j","Hash","executor","onNoObservers","proxy","ObserverProxy","subscribe","onError","implementsAnyMethods","methods","methods_1","method","observers","unsubscribes","observerCount","finalized","next","forEachObserver","observer","complete","nextOrObserver","unsub","unsubscribeOne","finalError","sendOne","errorPrefix","fnName","argumentNumber","optional","argName","validateNamespace","validateCallback","validateContextObject","context","validateArgCount","minCount","maxCount","argCount","argError","assert_1","out","high","stringLength","webpackJsonpFirebase","76","77","ba","ca","da","splice","propertyIsEnumerable","ea","fa","ha","q","ka","la","unshift","r","ma","ib","Nc","u","oa","qa","ra","sa","ta","ua","va","wa","xa","v","ya","za","Aa","Ca","Fa","Ga","Ha","Ba","Ia","Ja","Ka","La","x","Ma","Pa","Qa","Ra","Sa","Ta","Ua","Wa","Va","Xa","Ya","Za","eb","documentMode","jb","pa","fb","max","exec","parseInt","mb","$goog_Thenable","nb","ob","pb","sb","tb","qb","vb","xb","style","display","contentWindow","open","write","location","protocol","host","origin","parentNode","yb","zb","Ab","Bb","rb","set","Cb","Window","wb","z","Db","h","Eb","Fb","Gb","Hb","Ib","Kb","Jb","A","B","Lb","Mb","Nb","Ob","Qb","Rb","Sb","Tb","Ub","Vb","Pb","D","wc","xc","Wb","Xb","Yb","Zb","ac","bc","cc","dc","ec","fc","gc","hc","ic","jc","kc","lc","mc","pc","ja","oc","qc","rc","tc","uc","vc","getElementById","cssText","className","htmlFor","yc","lastIndexOf","zc","$b","Ac","createTextNode","nodeType","w","Bc","Cc","Dc","Ec","Number","Boolean","Fc","valueOf","isFinite","isNaN","Hc","Gc","substr","Ic","Jc","Kc","ia","Lc","C","Qc","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","nodeName","fromElement","toElement","pageX","pageY","Rc","defaultPrevented","Uc","capture","Tc","Vc","Wc","Xc","Yc","Zc","cd","dd","ed","Sc","fd","gd","hd","$c","Pc","jd","bd","kd","ld","E","md","removeEventListener","detachEvent","ad","nd","od","keyCode","returnValue","pd","handleEvent","F","G","qd","rd","sd","td","vd","wd","Ad","Dd","Cd","Bd","yd","Ed","S","P","Fd","Gd","H","zd","Hd","Da","Kd","Ld","Jd","Md","Id","Nd","Qd","Rd","Pd","Sd","Td","Ud","Vd","Ea","Wd","Xd","Od","Yd","Zd","$d","Uint8Array","Int32Array","ae","be","ge","ub","sc","yj","he","ie","je","ke","le","me","substring","decodeURIComponent","pe","qe","re","se","te","ne","ue","Ae","ve","Be","I","Ce","De","Ee","decodeURI","encodeURI","Fe","Ge","He","Ie","Je","Ke","Le","Me","toLowerCase","Ne","Oe","Qe","Re","XMLHttpRequest","ActiveXObject","Se","headers","Te","N","Ye","toUpperCase","Pe","J","Ze","$e","FormData","Xe","setRequestHeader","responseType","withCredentials","af","bf","ontimeout","send","abort","cf","df","ef","aa","ff","gf","We","statusText","xd","readyState","status","hf","responseText","kf","lf","mf","nf","of","Oc","pf","attributes","qf","tagName","rf","sf","XDomainRequest","responseXML","onprogress","tf","uf","kb","vf","href","wf","xf","yf","zf","Af","Bf","Cf","Df","screen","availHeight","availWidth","width","height","top","left","resizable","statusbar","toolbar","Ef","scrollbars","standalone","noreferrer","createEvent","initMouseEvent","dispatchEvent","bb","opener","focus","Ff","closed","Hf","If","Jf","Kf","Lf","K","Mf","Of","Nf","sort","userAgent","L","Pf","localStorage","Qf","setItem","removeItem","indexedDB","Rf","Sf","Tf","Uf","Vf","Wf","Xf","Yf","___jsl","CP","Zf","onLine","connection","$f","ag","visibilityState","bg","cg","toUTCString","M","eg","gg","hg","ig","jg","kg","lg","mg","ng","og","pg","qg","rg","sg","tg","ug","vg","wg","xg","yg","zg","Ag","Bg","Cg","Dg","Eg","Fg","continueUrl","canHandleCodeInApp","androidPackageName","androidMinimumVersion","androidInstallApp","iOSBundleId","Gg","sub","na","provider_id","sign_in_provider","Hg","iss","aud","exp","Lg","Kg","Na","Mg","Ng","Og","Pg","Qg","Rg","Sg","Tg","Ug","isNewUser","rawUserInfo","providerId","profile","login","screenName","Vg","Wg","idToken","accessToken","oauthToken","oauthTokenSecret","Yg","id_token","access_token","secret","oauth_token_secret","postBody","requestUri","ah","isOAuthProvider","Jg","bh","ch","credential","dh","eh","fh","gh","hh","Ig","ih","jh","mh","nh","Oa","Y","oh","temporaryProof","phoneNumber","sessionInfo","rh","auth","th","uh","oauthAccessToken","oauthIdToken","vh","wh","xh","eventId","urlResponse","sessionId","yh","zh","Ah","email","Bh","Ch","node","secureTokenEndpoint","secureTokenTimeout","Dh","secureTokenHeaders","Eh","firebaseEndpoint","firebaseTimeout","Fh","firebaseHeaders","Gh","Ih","Jh","Kh","Hh","Lh","gapi","client","request","Nh","Mh","Oh","grant_type","refresh_token","Ph","Qh","Rh","jf","Sh","Th","Q","Uh","identifier","continueUri","allProviders","Vh","Wh","authorizedDomains","Xh","Yh","sh","di","fi","gi","deleteProvider","hi","ii","needConfirmation","errorMessage","Xg","returnIdpCredential","ji","Zg","ki","$g","autoCreate","li","mi","oobCode","T","returnSecureToken","endpoint","ga","keyInvalid","ipRefererBlocked","INVALID_CUSTOM_TOKEN","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_EMAIL","INVALID_PASSWORD","USER_DISABLED","MISSING_PASSWORD","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","FEDERATED_USER_ID_ALREADY_LINKED","INVALID_MESSAGE_PAYLOAD","INVALID_RECIPIENT_EMAIL","INVALID_SENDER","EMAIL_NOT_FOUND","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","CORS_UNSUPPORTED","DYNAMIC_LINK_NOT_ACTIVATED","INVALID_APP_ID","TOO_MANY_ATTEMPTS_TRY_LATER","WEAK_PASSWORD","OPERATION_NOT_ALLOWED","USER_CANCELLED","CAPTCHA_CHECK_FAILED","INVALID_APP_CREDENTIAL","INVALID_CODE","INVALID_PHONE_NUMBER","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_APP_CREDENTIAL","MISSING_CODE","MISSING_PHONE_NUMBER","MISSING_SESSION_INFO","QUOTA_EXCEEDED","SESSION_EXPIRED","INVALID_CONTINUE_URI","MISSING_ANDROID_PACKAGE_NAME","MISSING_IOS_BUNDLE_ID","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","INVALID_CERT_HASH","wi","vi","ab","yi","zi","Ai","where","body","url","messageHandlersFilter","position","dontclear","restyle","setHideOnLeave","Bi","ping","Ci","Di","register","Gi","Fi","Ei","Hi","Ii","Ji","Ki","Li","Gf","RegExp","Mi","Ni","Pi","Qi","authEvent","Oi","webStorageSupport","Ri","reactNative","AsyncStorage","Si","Ti","Vi","errorCode","onupgradeneeded","createObjectStore","keyPath","onsuccess","Wi","Xi","objectStore","Yi","transaction","Zi","$i","cancel","aj","bj","cj","dj","ej","sessionStorage","fj","Browser","gj","Node","hj","ReactNative","ij","lj","kj","mj","jj","Ui","oj","nj","pj","qj","rj","X","sj","getItem","tj","uj","vj","wj","xj","oldValue","zj","Bj","Aj","Cj","Dj","Ej","Fj","Gj","fe","Ij","ibi","apn","appDisplayName","Kj","Hj","Lj","Jj","handleOpenURL","Mj","Oj","Nj","Pj","Qj","Rj","Sj","Tj","unknown","signInViaRedirect","linkViaRedirect","reauthViaRedirect","signInViaPopup","linkViaPopup","reauthViaPopup","Uj","xi","Vj","Wj","Xj","Yj","bk","dk","ck","ek","fk","gk","hk","user","ik","ak","jk","kk","lk","mk","ok","nk","pk","qk","rk","refreshToken","sk","expiresIn","tk","expires_in","expirationTime","uk","lastSignInTime","creationTime","vk","wk","uid","displayName","photoURL","xk","yk","apiKey","appName","authDomain","zk","Ak","Bk","U","R","Ck","V","Dk","Ek","Fk","Gk","start","Hk","Ik","Jk","Kk","emailVerified","isAnonymous","metadata","createdAt","lastLoginAt","providerData","Lk","Mk","Nk","Ok","Pk","Qk","Rk","Sk","Tk","Uk","si","Vk","providerUserInfo","rawId","photoUrl","Xk","Wk","additionalUserInfo","operationType","Yk","reload","Zk","$k","al","Z","bl","cl","dl","el","stsTokenManager","redirectEventId","fl","gl","hl","il","jl","ll","ml","nl","kl","ol","pl","ql","rl","sl","tl","ul","vl","logFramework","wl","xl","yl","$","zl","Al","Bl","Cl","Dl","currentUser","Fl","_lat","El","Gl","Hl","Il","Jl","Kl","Ll","Element","Ml","Nl","App","Ol","Pl","Ql","verify","Rl","theme","Sl","Tl","hasChildNodes","Ul","Vl","Wl","Xl","Yl","am","cm","grecaptcha","Infinity","Zl","render","bm","$l","dm","em","fm","gm","trim","some","$a","db","gb","hb","parseFloat","lb","compatMode","cellpadding","cellspacing","colspan","frameborder","maxlength","nonce","role","rowspan","usemap","valign","\"","\\","/","\b","\f","\n","\r","\t","\u000b","Mc","freeze","2","3","4","preventDefault","ud","timeStamp","msWriteProfilerMark","clear","ce","de","ee","we","xe","ye","ze","Ue","Ve","getResponse","response","mozResponseArrayBuffer","getResponseHeader","contentType","getAllResponseHeaders","dg","fg","abcd","toJSON","argument-error","app-not-authorized","app-not-installed","captcha-check-failed","code-expired","cordova-not-ready","cors-unsupported","credential-already-in-use","custom-token-mismatch","requires-recent-login","dynamic-link-not-activated","email-already-in-use","expired-action-code","cancelled-popup-request","internal-error","invalid-app-credential","invalid-app-id","invalid-user-token","invalid-auth-event","invalid-verification-code","invalid-continue-uri","invalid-cordova-configuration","invalid-custom-token","invalid-email","invalid-api-key","invalid-cert-hash","invalid-credential","invalid-persistence-type","invalid-message-payload","invalid-oauth-provider","invalid-oauth-client-id","unauthorized-domain","invalid-action-code","wrong-password","invalid-phone-number","invalid-recipient-email","invalid-sender","invalid-verification-id","missing-android-pkg-name","auth-domain-config-required","missing-app-credential","missing-verification-code","missing-continue-uri","missing-iframe-start","missing-ios-bundle-id","missing-phone-number","missing-verification-id","account-exists-with-different-credential","network-request-failed","no-auth-event","no-such-provider","operation-not-allowed","operation-not-supported-in-this-environment","popup-blocked","popup-closed-by-user","provider-already-linked","quota-exceeded","redirect-cancelled-by-user","redirect-operation-pending","user-token-expired","too-many-requests","unauthorized-continue-uri","unsupported-persistence-type","user-cancelled","user-not-found","user-disabled","user-mismatch","user-signed-out","weak-password","web-storage-unsupported","kh","password","lh","PROVIDER_ID","ph","operation","qh","verificationId","verificationCode","recaptchaToken","Content-Type","setApiKey","setToken","path","authType","Zh","$h","ai","deleteAttribute","requestType","bi","ci","ei","ni","newPassword","oi","pi","qi","ri","ti","recaptchaSiteKey","ui","put","add","getAll","openCursor","NONE","unsubscribe","Zj","confirm","users","localId","passwordHash","languages","language","userLanguage","execute","firstChild","Persistence","LOCAL","SESSION","Auth","User","util_1","util_2","util_3","util_4","util_5","util_6","storage_1","util_7","LUIDGenerator","sha1","sha1Bytes","buildLogMessage_","var_args","logger","firstLog_","enableLogging","logger_","persistent","SessionStorage","remove","logWrapper","prefix","fatal","warnIfPageIsSecure","warnAboutUnsupportedMethod","methodName","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","called_1","wrappedFn_1","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","each","bindCallback","doubleToIEEE754String","ln","bits","abs","pow","min","LN2","round","reverse","hexByteString","hexByte","isChromeExtensionContentScript","isWindowsStoreApp","Windows","UI","errorForServerCode","query","INTEGER_REGEXP_","intVal","exceptionGuard","callUserCallback","beingCrawled","search","exportPropGetter","fnGet","setTimeoutNonBlocking","time","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","begin","parent","pieces","child","childPathObj","childPieces","relativePath","outerPath","innerPath","outer","inner","comparePaths","right","leftKeys","rightKeys","cmp","equals","other","ValidationPath","errorPrefix_","parts_","byteLength_","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","Index_1","Node_1","LeafNode_1","PriorityIndex","compare","aPriority","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","NamedNode","MIN","maxPost","LeafNode","makePost","indexValue","priorityNode","Index","PRIORITY_INDEX","EMPTY_NODE","SortedMap_1","snap_1","PriorityIndex_1","KeyIndex_1","IndexMap_1","comparators_1","ChildrenNode","children_","priorityNode_","indexMap_","lazyHash_","validatePriorityNode","SortedMap","NAME_COMPARATOR","IndexMap","Default","isLeafNode","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","front","hasChild","updateImmediateChild","newChildNode","namedNode","newChildren","newIndexMap","newPriority","removeFromIndexes","insert","addToIndexes","updateChild","newImmediateChild","numChildren","count","exportFormat","numKeys","maxKey","allIntegerKeys","forEachChild","childNode","hash","toHash_1","priorityHashText","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","iterator","Wrap","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","KEY_INDEX","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","KeyIndex","__EMPTY_NODE","__childrenNodeConstructor","Path_1","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","isValidPriority","priority","validateFirebaseDataArg","validateFirebaseData","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","repoInfo","validateCredential","cred","validateBoolean","bool","validateString","string","validateObject","validateObjectContainsKey","opt_type","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","Server","forServerTaggedQuery","Change","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","json","ChildrenNode_1","jsonLeaf","USE_HINZE","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","childSet_1","buildChildSet","NAME_ONLY_COMPARATOR","sortedChildSet","getCompare",".priority","DOMStorageWrapper_1","MemoryStorage_1","createStoragefor","domStorageName","domStorage","DOMStorageWrapper","MemoryStorage","PersistentStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","oldWrapped","newWrapped","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","hasNext","LLRBNode","color","RED","copy","reverseTraversal","min_","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues_1","nodeFromJSON_1","SparseSnapshotTree_1","SyncTree_1","SnapshotHolder_1","AuthTokenProvider_1","StatsManager_1","StatsReporter_1","StatsListener_1","EventQueue_1","PersistentConnection_1","ReadonlyRestClient_1","Database_1","Repo","repoInfo_","forceRestClient","dataUpdateCount","statsListener_","eventQueue_","EventQueue","nextWriteId_","interceptServerDataCallback_","onDisconnect_","SparseSnapshotTree","persistentConnection_","authTokenProvider","AuthTokenProvider","stats_","StatsManager","getCollection","server_","ReadonlyRestClient","onDataUpdate_","onConnectStatus_","authOverride","PersistentConnection","onServerInfoUpdate_","addTokenChangeListener","refreshAuthToken","statsReporter_","getOrCreateReporter","StatsReporter","transactions_init_","infoData_","SnapshotHolder","infoSyncTree_","SyncTree","startListening","tag","currentHashFn","onComplete","infoEvents","getNode","applyServerOverwrite","stopListening","updateInfo_","serverSyncTree_","listen","events","raiseEventsForChangedPath","unlisten","secure","serverTime","offsetNode","offset","generateServerValues","generateWithValues","timestamp","isMerge","taggedChildren","raw","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","changedChildren","applyServerMerge","snap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","updates","updateSnapshot","getNextWriteId_","setWithPriority","newVal","log_","serverValues","newNodeUnresolved","resolveDeferredValueSnapshot","writeId","applyUserOverwrite","queueEvents","errorReason","success","clearEvents","ackUserWrite","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","merge","changedPath","resolvedOnDisconnectTree","resolveDeferredValueTree","forEachTree","Empty","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","eventRegistration","addEventRegistration","raiseEventsAtPath","removeEventCallbackForQuery","removeEventRegistration","interrupt","resume","stats","showDelta","StatsListener","longestName","reduce","previousValue","currentValue","stat","statsIncrementCounter","metric","incrementCounter","includeStat","__database","Database","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","onDisconnect_1","TransactionResult_1","NextPushId_1","Query_1","Repo_1","QueryParams_1","validation_1","SyncPoint_1","Reference","repo","QueryParams","DEFAULT","getKey","getParent","parentPath","getRoot","databaseProp","database","objectToMerge","newObjectToMerge","transactionUpdate","applyLocally","promiseComplete","committed","TransactionResult","startTransaction","setPriority","nextPushId","thennablePushRef","pushRef","onDisconnect","OnDisconnect","Query","__referenceConstructor","SyncPoint","DataSnapshot","ref_","index_","exportVal","exists","childPathString","childPath","childRef","hasChildren","getRef","emptyChildrenSingleton","EmptyChildren","ImmutableTree","children","fromObject","tree","childSnap","findRootMostMatchingPathAndValue","childExistingPathAndValue","findRootMostValueAndPath","subtree","childTree","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","Change_1","IndexedFilter","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","getIndex","StatsCollection_1","hashString","collections_","StatsCollection","creatorFunction","reporters_","parser_1","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","dbUrl","databaseFromApp","parseRepoInfo","createRepo","deleteRepo","appRepos","toURLString","Reference_1","RepoManager_1","repo_","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","decodePath","pathStringDecoded","piece","RepoInfo_1","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","RepoInfo","port","colonInd","slashInd","Constants_1","persistenceKey","internalHost","needsQueryParam","isCacheableHost","isDemoHost","isCustomHost","updateHost","newHost","connectionURL","connURL","pairs","ValueIndex_1","PathIndex_1","EventRegistration_1","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","PathIndex","VALUE_INDEX","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","getQueryParams","cancelCallbackOrContext","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","ValueEventRegistration","ChildEventRegistration","valueCallback","userCallback","cancelOrContext","firstCall","onceCallback","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","ValueIndex","valueNode","_defaultIndexMap","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","SortedMap_2","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","middle","base12","buildPennant","chunkSize","attachPennant","pennant","isOne","indexPath_","extractChild","aChild","bChild","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","CountedSet_1","CountedSet","self_1","prefixPath","func","Operation_1","Overwrite","OVERWRITE","operationForChild","CacheNode_1","ViewCache_1","View_1","views_","applyOperation","writesCache","optCompleteServerCache","view","events_1","serverCache","serverCacheComplete","eventCache","calcCompleteEventCache","eventCacheComplete","calcCompleteEventChildren","viewCache","ViewCache","View","getInitialEvents","cancelError","removed","cancelEvents","hadCompleteView","hasCompleteView","viewQueryId","getQuery","loadsAllData","getQueryViews","getCompleteServerCache","viewForQuery","getCompleteView","viewExistsForQuery","eventCache_","serverCache_","updateEventSnap","eventSnap","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","collection_","last_","newStats","delta","app_1","VisibilityMonitor_1","OnlineMonitor_1","Connection_1","ServerActions_1","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","visible_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","VisibilityMonitor","onVisible_","OnlineMonitor","onOnline_","sendRequest","onResponse","curReqNum","msg","isDefault","listenSpec","hashFn","sendListen_","req","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","token_1","authMethod","requestData","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","reportStats","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","handleTimestamp_","sendConnectStats_","restoreState_","establishConnection_","visible","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage_1","onReady_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","forceRefresh","Connection","serverTimeOffset","normalizedPathString","statusCode","explanation","notifyForInvalidToken","queries","clientName","currentlyOnline","ServerActions","EventEmitter","allowedEvents_","listeners_","trigger","validateEventType_","eventData","getInitialEvent","et","TransportManager_1","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","TransportManager","start_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","onMessage","closeConnections_","PacketReceiver_1","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","BrowserPollConnection","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","PacketReceiver","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","incrementIncomingBytes_","sendNewPolls","closeAfter","pN","handleResponse","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","shutdown_","myDisconnFrame","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","iframeContents","iframe","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","rstate","setWebSocketImpl","impl","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","User-Agent","platform","mySock","onopen","onclose","handleIncomingFrame","isOldAndroid","oldAndroidRegex","oldAndroidMatch","previouslyFailed","isInMemoryStorage","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","resetKeepAlive","remainingData","sendString_","responsesRequiredToBeHealthy","healthyTimeout","IndexedFilter_1","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","startName","endName","registerDatabase","instance","unused","TEST_ACCESS","DataSnapshot_1","domStorage_","prefix_","prefixedName_","storedVal","cache_","PUSH_CHARS","lastPushTime","lastRandChars","duplicateTime","timeStampChars","Event_1","callback_","cancelCallback_","context_","respondsTo","change","DataEvent","getEventRunner","ctx","getEventType","cancelCB_1","cb_1","createCancelEvent","CancelEvent","hasAnyCallback","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","thisKey","getPath","AckUserWrite_1","ImmutableTree_1","ListenComplete_1","Merge_1","Overwrite_1","WriteTree_1","listenProvider_","syncPointTree_","pendingWriteTree_","WriteTree","tagToQueryMap_","queryToTagMap_","newData","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","Merge","revert","getWrite","removeWrite","affectedTree_1","AckUserWrite","applyListenComplete","ListenComplete","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","completeCache","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","createListenerForView_","queryForListening_","tagForQuery_","queryToRemove","tagToRemove","removeTags_","writeIdsToExclude","writeTree","maybeChildSyncPoint","childMap","views_1","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","affectedTree","ACK_USER_WRITE","LISTEN_COMPLETE","MERGE","ViewProcessor_1","EventGenerator_1","query_","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","ViewProcessor","initialServerCache","initialEventCache","newServerCache","newEventCache","viewCache_","eventGenerator_","EventGenerator","cache","path_1","registration","maybeEvent","existing","completeServerCache","oldViewCache","assertIndexed","generateEventsForChanges_","changes","initialChanges","registrations","generateEventsForChanges","ChildChangeAccumulator_1","CompleteChildSource_1","ProcessorResult","filter_","newViewCache","filterServerNode","accumulator","ChildChangeAccumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","serverNode","completeChildren","completeEventChildren","completeNode","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","calcCompleteChild","changedSnap","oldServerSnap","serverFilter","newServerNode","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","getCompleteChild","newEventSnap","cacheHasChild_","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","changeMap_","oldChange","oldType","NoCompleteChildSource_","getChildAfterChild","writes_","optCompleteServerCache_","completeServerData","nodes","calcIndexedSlice","eventRegistrations","moves","generateEventsForType_","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","aWrapped","bWrapped","CompoundWrite_1","visibleWrites_","CompoundWrite","allWrites_","lastWriteId_","WriteTreeRef","addWrite","addWrites","record","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","getCompleteNode","treePath","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","shadowingNode","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","writeTree_","existingServerCache","rootmost","rootMostPath","newWrite","applySubtreeWrite_","priorityWrite_1","rootNode_","newSnapshotNode","app_","removeTokenChangeListener","counters_","amount","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","collection","statsToReport_","reportStats_","reportedStats","haveStatsToReport","eventLists_","recursionDepth_","eventDataList","currList","eventPath","EventList","raiseQueuedEventsMatchingPredicate_","sentAll","eventList","raise","events_","eventFn","EventEmitter_1","hidden","visibilityChange","online_","BrowserPollConnection_1","WebSocketConnection_1","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","this_1","toProcess","getListenId_","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","queryStringParameters","authTokenData","authToken","xhr","LimitedFilter_1","RangedFilter_1","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","isViewFromLeft","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","getLimit","copy_","newLimit","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","LimitedFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","rangedFilter_","reverse_","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","TransactionStatus","Tree_1","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","Tree","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","forEachAncestor","abortTransactionsOnNode_","forEachDescendant","lastSent","TreeNode","childCount","parent_","pathObj","updateParents_","includeSelf","childrenFirst","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef","116","117","toBase64","arrayBuffer","uint8Version","registerMessaging","factoryMethod","sw_controller","window_controller","namespaceExports","Messaging","_a","CODES","AVAILABLE_IN_WINDOW","AVAILABLE_IN_SW","SHOULD_BE_INHERITED","BAD_SENDER_ID","INCORRECT_GCM_SENDER_ID","PERMISSION_DEFAULT","PERMISSION_BLOCKED","UNSUPPORTED_BROWSER","NOTIFICATIONS_BLOCKED","FAILED_DEFAULT_REGISTRATION","SW_REGISTRATION_EXPECTED","GET_SUBSCRIPTION_FAILED","INVALID_SAVED_TOKEN","SW_REG_REDUNDANT","TOKEN_SUBSCRIBE_FAILED","TOKEN_SUBSCRIBE_NO_TOKEN","TOKEN_SUBSCRIBE_NO_PUSH_SET","USE_SW_BEFORE_GET_TOKEN","INVALID_DELETE_TOKEN","DELETE_TOKEN_NOT_FOUND","DELETE_SCOPE_NOT_FOUND","BG_HANDLER_FUNCTION_EXPECTED","NO_WINDOW_CLIENT_TO_MSG","UNABLE_TO_RESUBSCRIBE","NO_FCM_TOKEN_FOR_RESUBSCRIBE","FAILED_TO_DELETE_TOKEN","NO_SW_IN_REG","BAD_SCOPE","BAD_VAPID_KEY","BAD_SUBSCRIPTION","BAD_TOKEN","BAD_PUSH_SET","FAILED_DELETE_VAPID_KEY","ERROR_MAP","codes","array_buffer_to_base64","FCM_APPLICATION_SERVER_KEY","SUBSCRIPTION_DETAILS","userVisibleOnly","applicationServerKey","fcm_details","ENDPOINT","APPLICATION_SERVER_KEY","SUBSCRIPTION_OPTIONS","FCM_TOKEN_OBJ_STORE","token_manager_TokenManager","TokenManager","errorFactory_","openDbPromise_","openDatabase_","DB_NAME","createIndex","unique","closeDatabase","getTokenDetailsFromToken","fcmToken","getTokenDetailsFromSWScope_","swScope","scopeRequest","getAllTokenDetailsForSenderId_","senderId","senderIdTokens","cursorRequest","cursor","continue","subscribeToFCM","subscription","pushSet","p256dh","fcmSubscribeBody","Headers","append","subscribeOptions","fetch","fcmTokenResponse","isSameSubscription_","masterTokenDetails","saveTokenDetails_","swRegistration","fcmPushSet","details","scope","fcmSenderId","getSavedToken","ServiceWorkerRegistration","allTokenDetails","tokenDetails","pushManager","getSubscription","createToken","fcmTokenDetails","deleteToken","token_manager","SENDER_ID_OPTION_NAME","controller_interface_ControllerInterface","ControllerInterface","messagingSenderId_","tokenManager_","currentPermission","getNotificationPermission_","notification_permission","getSWRegistration_","requestPermission","useServiceWorker","optError","optCompleted","onTokenRefresh","setBackgroundMessageHandler","Notification","permission","getTokenManager","controller_interface","PARAMS","TYPE_OF_MSG","DATA","msgType","PUSH_MSG_RECEIVED","NOTIFICATION_CLICKED","createNewMsg","msgData","worker_page_message","TYPES_OF_MSG","default_sw","window_controller_WindowController","WindowController","registrationToUse_","manifestCheckPromise_","messageObserver_","tokenRefreshObserver_","onTokenRefresh_","setupSWMessageListener_","isSupported_","manifestCheck_","manifestTag","querySelector","manifestContent","managePermissionResult","permissionPromise","waitForRegistrationToActivate_","serviceWorker","installing","waiting","state","stateChangeListener","browserErrorMessage","workerPageMessage","pushMessage","PushSubscription","sw_controller___extends","sw_controller_SWController","SWController","onPush_","onSubChange_","onNotificationClick_","bgMessageHandler_","msgPayload","handleMsgPromise","hasVisibleClients_","hasVisibleClients","notification","sendMessageToWindowClients_","notificationDetails","getNotificationData_","notificationTitle","showNotification","waitUntil","promiseChain","tokenManager","newSubscription","stopImmediatePropagation","clickAction","getWindowClient_","windowClient","clients","openWindow","internalMsg","attemptToMessageClient_","notificationInformation","assign","URL","matchAll","includeUncontrolled","clientList","suitableClient","esm","118","119","prependCode","FirebaseStorageError","Code","UNKNOWN","objectNotFound","OBJECT_NOT_FOUND","quotaExceeded","bucket","unauthenticated","UNAUTHENTICATED","unauthorized","UNAUTHORIZED","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","error_canceled","CANCELED","invalidUrl","INVALID_URL","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","cannotSliceBlob","CANNOT_SLICE_BLOB","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","noDownloadURL","NO_DOWNLOAD_URL","invalidArgument","INVALID_ARGUMENT","invalidArgumentCount","argMin","argMax","real","countPart","plural","INVALID_ARGUMENT_COUNT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","formatValidator","stringFormat","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","dataFromString","StringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","valid","lo","percentEncodedBytes_","hasMinus","hasUnder","invalidChar","hasPlus","hasSlash","string_DataURLParts","rest","endsWith","end","taskStateFromInternalTaskState","InternalTaskState","RUNNING","PAUSING","CANCELING","TaskState","PAUSED","SUCCESS","ERROR","make","resolver","promise_external_resolve","promise_external_reject","isDef","isJustDef","isFunction","isObject","isNonArrayObject","isString","isNumber","isNativeBlob","isNativeBlobDefined","Blob","jsonObjectOrNull","path_parent","canonicalChildPath","component","lastComponent","makeNormalUrl","urlPart","domainBase","apiBaseUrl","makeDownloadUrl","downloadBase","makeUploadUrl","apiUploadBaseUrl","makeQueryString","encode","queryPart","nextPart","noXform_","xformPath","fullPath","getMappings","mappingsXformPath","xformSize","size","xformTokens","tokens","alt","mappings_","mappings","Mapping","nameMapping","xform","sizeMapping","addRef","authWrapper","generateRef","loc","location_Location","makeStorageReference","fromResource","resource","mapping","local","server","fromResourceString","resourceString","toResourceString","writable","metadataValidator","validate","specs","passed","minArgs","maxArgs","validator","and_","v1","v2","stringSpec","opt_validator","opt_optional","stringValidator","args_ArgSpec","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","sliceBlob","blob","webkitSlice","mozSlice","array_contains","elem","array_clone","arraylike","handlerCheck","cndn","metadataHandler","handler","text","sharedErrorHandler","errorHandler","newErr","getStatus","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","getMetadata","fullServerUrl","maxOperationRetryTime","requestInfo","RequestInfo","updateMetadata","deleteObject","successCodes","determineContentType_","metadataForUpload_","opt_metadata","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","metadataString","preBlobPart","postBlobPart","blob_FbsBlob","maxUploadRetryTime","uploadData","checkResumeHeader_","opt_allowed","createResumableUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","ResumableUploadStatus","continueResumableUpload","opt_status","opt_progressCallback","uploadStatus","newCurrent","current","bytesToUpload","total","bytesLeft","startByte","endByte","uploadCommand","X-Goog-Upload-Offset","progressCallback","async_async","argsToForward","canceled","cancelState","triggerCallback","triggeredCallback","callWithDelay","millis","timeoutId","hitTimeout","waitSeconds","waitMillis","stop","wasTimeout","stopped","addAuthHeader_","addVersionHeader_","number","makeRequest","pool","request_NetworkRequest","additionalRetryCodes","factory","opt_url","service_Service","xhriopool_XhrIoPool","registerStorage","TaskEvent","Storage","reference_Reference","STORAGE_TYPE","ErrorCode","defaultMaxOperationRetryTime","defaultMaxUploadRetryTime","minSafeInteger","code_","message_","serverResponse_","codeProp","codeEquals","serverResponse","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","INVALID_CHECKSUM","INVALID_EVENT_NAME","NO_DEFAULT_BUCKET","opt_contentType","DataURLParts","STATE_CHANGED","xhrio_network_NetworkXhrIo","NetworkXhrIo","sent_","xhr_","errorCode_","NO_ERROR","sendPromise_","ABORT","NETWORK_ERROR","opt_body","opt_headers","getErrorCode","getResponseText","addUploadProgressListener","upload","removeUploadProgressListener","XhrIoPool","createXhrIo","Location","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","gsModify","httpModify","gsRegex","gsIndices","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","bucketValue","pathValue","opt_local","opt_writable","opt_xform","ArgSpec","FbsBlob","opt_elideCopy","blobType","data_","byteLength","size_","type_","realBlob","sliced","buffer","blobby","uint8Arrays","finalLength_1","merged_1","index_1","observer_Observer","Observer","opt_error","opt_complete","UploadTaskSnapshot","bytesTransferred","totalBytes","urls","task_UploadTask","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","getAuthToken","createRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","metadataRequest","multipartRequest","transferred","old","notifyObservers_","wasPaused","externalState","completed","typeValidator","_p","nextOrObserverValidator","nextValidator","observerValidator","nextOrObserverMessage","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","notifyObserver_","finishPromise_","triggered","pause","newRef","newPath","throwIfRoot_","putString","getDownloadURL","failrequest_FailRequest","FailRequest","appDelete","requestmap_RequestMap","RequestMap","map_","id_","addRequest","unmap","authwrapper_AuthWrapper","AuthWrapper","maker","requestMaker","bucket_","deleted_","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","_error","deleteApp","setMaxUploadRetryTime","setMaxOperationRetryTime","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","progressListener","progressEvent","lengthComputable","RequestEndStatus","hitServer","isRetryStatusCode_","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","Service","authWrapperBucket","internals_","service_ServiceInternals","ServiceInternals"],"mappings":";;;;;AAKA,GAAIA,UAAW,WACL,GAAIC,OAA2B,KAAXA,EAAyBC,KAAOD,CACtD,OAAgB,UAAUE,GCgClC,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAE,OAGA,IAAAC,GAAAF,EAAAD,IACAI,EAAAJ,EACAK,GAAA,EACAH,WAUA,OANAJ,GAAAE,GAAAM,KAAAH,EAAAD,QAAAC,IAAAD,QAAAH,GAGAI,EAAAE,GAAA,EAGAF,EAAAD,QA1DA,GAAAK,GAAAX,EAAA,oBACAA,GAAA,8BAAAY,EAAAC,EAAAC,GAIA,IADA,GAAAV,GAAAW,EAAAC,EAAAR,EAAA,EAAAS,KACQT,EAAAI,EAAAM,OAAoBV,IAC5BO,EAAAH,EAAAJ,GACAW,EAAAJ,IACAE,EAAAG,KAAAD,EAAAJ,GAAA,IAEAI,EAAAJ,GAAA,CAEA,KAAAX,IAAAS,GACAQ,OAAAC,UAAAC,eAAAb,KAAAG,EAAAT,KACAF,EAAAE,GAAAS,EAAAT,GAIA,KADAO,KAAAC,EAAAC,EAAAC,GACAG,EAAAC,QACAD,EAAAO,SAEA,IAAAV,EACA,IAAAN,EAAA,EAAYA,EAAAM,EAAAI,OAA2BV,IACvCQ,EAAAb,IAAAsB,EAAAX,EAAAN,GAGA,OAAAQ,GAIA,IAAAX,MAGAc,GACAO,EAAA,EAiHA,OApFAvB,GAAAwB,EAAA,SAAAZ,GA+BA,QAAAa,KAEAC,EAAAC,QAAAD,EAAAE,OAAA,KACAC,aAAAC,EACA,IAAAC,GAAAf,EAAAJ,EACA,KAAAmB,IACAA,GACAA,EAAA,GAAAC,MAAA,iBAAApB,EAAA,aAEAI,EAAAJ,OAAAqB,IAvCA,GAAAC,GAAAlB,EAAAJ,EACA,QAA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AkwH,EAAAzyH,UAAA,OACA0C,IAAA,WACA,MAAAwC,MAAAu3F,IAEAh6F,YAAA,EACAD,cAAA,IAEAzC,OAAAwC,eAAAkwH,EAAAzyH,UAAA,YACA0C,IAAA,WACA,MAAAwC,MAAAytH,IAEAlwH,YAAA,EACAD,cAAA,IAEAiwH,KAMAG,GAAA,WACA,QAAAC,GAAA/qH,GACA5C,KAAA6qH,GAAAjoH,EAUA,MAJA+qH,GAAA7yH,UAAAuH,OAAA,WAEA,MADArC,MAAA6qH,GAAA5E,EAAAkF,YACArW,MAAAl5G,KAEA+xH,If7IAxvH,GAAA,gBAAA2hH,EAyBA,IAAAI,IAAA,SAiBAJ,IAAAnQ,GAAA,YnBmoHG,MACO,MAAM3xG,GACN,KAAUrC,OACR","file":"firebase.js","sourcesContent":["/*!\n * @license Firebase v4.6.1\n * Build: rev-0ea11f2\n * Terms: https://firebase.google.com/terms/\n */\nvar firebase = (function() {\n var window = typeof window === 'undefined' ? self : window;\n return /******/ (function(modules) { // webpackBootstrap\n/******/ \t// install a JSONP callback for chunk loading\n/******/ \tvar parentJsonpFunction = window[\"webpackJsonpFirebase\"];\n/******/ \twindow[\"webpackJsonpFirebase\"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {\n/******/ \t\t// add \"moreModules\" to the modules object,\n/******/ \t\t// then flag all \"chunkIds\" as loaded and fire callback\n/******/ \t\tvar moduleId, chunkId, i = 0, resolves = [], result;\n/******/ \t\tfor(;i < chunkIds.length; i++) {\n/******/ \t\t\tchunkId = chunkIds[i];\n/******/ \t\t\tif(installedChunks[chunkId]) {\n/******/ \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n/******/ \t\t\t}\n/******/ \t\t\tinstalledChunks[chunkId] = 0;\n/******/ \t\t}\n/******/ \t\tfor(moduleId in moreModules) {\n/******/ \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n/******/ \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\tif(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);\n/******/ \t\twhile(resolves.length) {\n/******/ \t\t\tresolves.shift()();\n/******/ \t\t}\n/******/ \t\tif(executeModules) {\n/******/ \t\t\tfor(i=0; i < executeModules.length; i++) {\n/******/ \t\t\t\tresult = __webpack_require__(__webpack_require__.s = executeModules[i]);\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\treturn result;\n/******/ \t};\n/******/\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// objects to store loaded and loading chunks\n/******/ \tvar installedChunks = {\n/******/ \t\t5: 0\n/******/ \t};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/ \t// This file contains only the entry chunk.\n/******/ \t// The chunk loading function for additional chunks\n/******/ \t__webpack_require__.e = function requireEnsure(chunkId) {\n/******/ \t\tvar installedChunkData = installedChunks[chunkId];\n/******/ \t\tif(installedChunkData === 0) {\n/******/ \t\t\treturn new Promise(function(resolve) { resolve(); });\n/******/ \t\t}\n/******/\n/******/ \t\t// a Promise means \"currently loading\".\n/******/ \t\tif(installedChunkData) {\n/******/ \t\t\treturn installedChunkData[2];\n/******/ \t\t}\n/******/\n/******/ \t\t// setup Promise in chunk cache\n/******/ \t\tvar promise = new Promise(function(resolve, reject) {\n/******/ \t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n/******/ \t\t});\n/******/ \t\tinstalledChunkData[2] = promise;\n/******/\n/******/ \t\t// start chunk loading\n/******/ \t\tvar head = document.getElementsByTagName('head')[0];\n/******/ \t\tvar script = document.createElement('script');\n/******/ \t\tscript.type = 'text/javascript';\n/******/ \t\tscript.charset = 'utf-8';\n/******/ \t\tscript.async = true;\n/******/ \t\tscript.timeout = 120000;\n/******/\n/******/ \t\tif (__webpack_require__.nc) {\n/******/ \t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n/******/ \t\t}\n/******/ \t\tscript.src = __webpack_require__.p + \"\" + chunkId + \".js\";\n/******/ \t\tvar timeout = setTimeout(onScriptComplete, 120000);\n/******/ \t\tscript.onerror = script.onload = onScriptComplete;\n/******/ \t\tfunction onScriptComplete() {\n/******/ \t\t\t// avoid mem leaks in IE.\n/******/ \t\t\tscript.onerror = script.onload = null;\n/******/ \t\t\tclearTimeout(timeout);\n/******/ \t\t\tvar chunk = installedChunks[chunkId];\n/******/ \t\t\tif(chunk !== 0) {\n/******/ \t\t\t\tif(chunk) {\n/******/ \t\t\t\t\tchunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));\n/******/ \t\t\t\t}\n/******/ \t\t\t\tinstalledChunks[chunkId] = undefined;\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t\thead.appendChild(script);\n/******/\n/******/ \t\treturn promise;\n/******/ \t};\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// on error function for async loading\n/******/ \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = 57);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(__webpack_require__(28));\n__export(__webpack_require__(29));\n__export(__webpack_require__(20));\n__export(__webpack_require__(65));\n__export(__webpack_require__(66));\n__export(__webpack_require__(67));\n__export(__webpack_require__(68));\n__export(__webpack_require__(30));\n__export(__webpack_require__(69));\n__export(__webpack_require__(31));\n__export(__webpack_require__(70));\n__export(__webpack_require__(71));\n__export(__webpack_require__(73));\n__export(__webpack_require__(74));\n__export(__webpack_require__(75));\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 1 */,\n/* 2 */,\n/* 3 */,\n/* 4 */,\n/* 5 */,\n/* 6 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../util/dist/cjs/index.js\nvar cjs = __webpack_require__(0);\nvar cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);\n\n// CONCATENATED MODULE: ../app/dist/esm/src/firebaseApp.js\n/**\n * Copyright 2017 Google Inc.\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\nvar contains = function (obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\nvar DEFAULT_ENTRY_NAME = '[DEFAULT]';\n// An array to capture listeners before the true auth functions\n// exist\nvar tokenListeners = [];\n/**\n * Global context object for a collection of services using\n * a shared authentication state.\n */\nvar firebaseApp_FirebaseAppImpl = /** @class */ (function () {\n function FirebaseAppImpl(options, name, firebase_) {\n this.firebase_ = firebase_;\n this.isDeleted_ = false;\n this.services_ = {};\n this.name_ = name;\n this.options_ = Object(cjs[\"deepCopy\"])(options);\n this.INTERNAL = {\n getUid: function () { return null; },\n getToken: function () { return Promise.resolve(null); },\n addAuthTokenListener: function (callback) {\n tokenListeners.push(callback);\n // Make sure callback is called, asynchronously, in the absence of the auth module\n setTimeout(function () { return callback(null); }, 0);\n },\n removeAuthTokenListener: function (callback) {\n tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; });\n }\n };\n }\n Object.defineProperty(FirebaseAppImpl.prototype, \"name\", {\n get: function () {\n this.checkDestroyed_();\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseAppImpl.prototype, \"options\", {\n get: function () {\n this.checkDestroyed_();\n return this.options_;\n },\n enumerable: true,\n configurable: true\n });\n FirebaseAppImpl.prototype.delete = function () {\n var _this = this;\n return new Promise(function (resolve) {\n _this.checkDestroyed_();\n resolve();\n })\n .then(function () {\n _this.firebase_.INTERNAL.removeApp(_this.name_);\n var services = [];\n Object.keys(_this.services_).forEach(function (serviceKey) {\n Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) {\n services.push(_this.services_[serviceKey][instanceKey]);\n });\n });\n return Promise.all(services.map(function (service) {\n return service.INTERNAL.delete();\n }));\n })\n .then(function () {\n _this.isDeleted_ = true;\n _this.services_ = {};\n });\n };\n /**\n * Return a service instance associated with this app (creating it\n * on demand), identified by the passed instanceIdentifier.\n *\n * NOTE: Currently storage is the only one that is leveraging this\n * functionality. They invoke it by calling:\n *\n * ```javascript\n * firebase.app().storage('STORAGE BUCKET ID')\n * ```\n *\n * The service name is passed to this already\n * @internal\n */\n FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) {\n if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; }\n this.checkDestroyed_();\n if (!this.services_[name]) {\n this.services_[name] = {};\n }\n if (!this.services_[name][instanceIdentifier]) {\n /**\n * If a custom instance has been defined (i.e. not '[DEFAULT]')\n * then we will pass that instance on, otherwise we pass `null`\n */\n var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME\n ? instanceIdentifier\n : undefined;\n var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier);\n this.services_[name][instanceIdentifier] = service;\n }\n return this.services_[name][instanceIdentifier];\n };\n /**\n * Callback function used to extend an App instance at the time\n * of service instance creation.\n */\n FirebaseAppImpl.prototype.extendApp = function (props) {\n var _this = this;\n // Copy the object onto the FirebaseAppImpl prototype\n Object(cjs[\"deepExtend\"])(this, props);\n /**\n * If the app has overwritten the addAuthTokenListener stub, forward\n * the active token listeners on to the true fxn.\n *\n * TODO: This function is required due to our current module\n * structure. Once we are able to rely strictly upon a single module\n * implementation, this code should be refactored and Auth should\n * provide these stubs and the upgrade logic\n */\n if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) {\n tokenListeners.forEach(function (listener) {\n _this.INTERNAL.addAuthTokenListener(listener);\n });\n tokenListeners = [];\n }\n };\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n FirebaseAppImpl.prototype.checkDestroyed_ = function () {\n if (this.isDeleted_) {\n error('app-deleted', { name: this.name_ });\n }\n };\n return FirebaseAppImpl;\n}());\n// Prevent dead-code elimination of these methods w/o invalid property\n// copying.\n(firebaseApp_FirebaseAppImpl.prototype.name && firebaseApp_FirebaseAppImpl.prototype.options) ||\n firebaseApp_FirebaseAppImpl.prototype.delete ||\n console.log('dc');\n/**\n * Return a firebase namespace object.\n *\n * In production, this will be called exactly once and the result\n * assigned to the 'firebase' global. It may be called multiple times\n * in unit tests.\n */\nfunction createFirebaseNamespace() {\n var apps_ = {};\n var factories = {};\n var appHooks = {};\n // A namespace is a plain JavaScript Object.\n var namespace = {\n // Hack to prevent Babel from modifying the object returned\n // as the firebase namespace.\n __esModule: true,\n initializeApp: initializeApp,\n app: app,\n apps: null,\n Promise: Promise,\n SDK_VERSION: '4.6.1',\n INTERNAL: {\n registerService: registerService,\n createFirebaseNamespace: createFirebaseNamespace,\n extendNamespace: extendNamespace,\n createSubscribe: cjs[\"createSubscribe\"],\n ErrorFactory: cjs[\"ErrorFactory\"],\n removeApp: removeApp,\n factories: factories,\n useAsService: useAsService,\n Promise: Promise,\n deepExtend: cjs[\"deepExtend\"]\n }\n };\n // Inject a circular default export to allow Babel users who were previously\n // using:\n //\n // import firebase from 'firebase';\n // which becomes: var firebase = require('firebase').default;\n //\n // instead of\n //\n // import * as firebase from 'firebase';\n // which becomes: var firebase = require('firebase');\n Object(cjs[\"patchProperty\"])(namespace, 'default', namespace);\n // firebase.apps is a read-only getter.\n Object.defineProperty(namespace, 'apps', {\n get: getApps\n });\n /**\n * Called by App.delete() - but before any services associated with the App\n * are deleted.\n */\n function removeApp(name) {\n var app = apps_[name];\n callAppHooks(app, 'delete');\n delete apps_[name];\n }\n /**\n * Get the App object for a given name (or DEFAULT).\n */\n function app(name) {\n name = name || DEFAULT_ENTRY_NAME;\n if (!contains(apps_, name)) {\n error('no-app', { name: name });\n }\n return apps_[name];\n }\n Object(cjs[\"patchProperty\"])(app, 'App', firebaseApp_FirebaseAppImpl);\n /**\n * Create a new App instance (name must be unique).\n */\n function initializeApp(options, name) {\n if (name === undefined) {\n name = DEFAULT_ENTRY_NAME;\n }\n else {\n if (typeof name !== 'string' || name === '') {\n error('bad-app-name', { name: name + '' });\n }\n }\n if (contains(apps_, name)) {\n error('duplicate-app', { name: name });\n }\n var app = new firebaseApp_FirebaseAppImpl(options, name, namespace);\n apps_[name] = app;\n callAppHooks(app, 'create');\n return app;\n }\n /*\n * Return an array of all the non-deleted FirebaseApps.\n */\n function getApps() {\n // Make a copy so caller cannot mutate the apps list.\n return Object.keys(apps_).map(function (name) { return apps_[name]; });\n }\n /*\n * Register a Firebase Service.\n *\n * firebase.INTERNAL.registerService()\n *\n * TODO: Implement serviceProperties.\n */\n function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) {\n // Cannot re-register a service that already exists\n if (factories[name]) {\n error('duplicate-service', { name: name });\n }\n // Capture the service factory for later service instantiation\n factories[name] = createService;\n // Capture the appHook, if passed\n if (appHook) {\n appHooks[name] = appHook;\n // Run the **new** app hook on all existing apps\n getApps().forEach(function (app) {\n appHook('create', app);\n });\n }\n // The Service namespace is an accessor function ...\n var serviceNamespace = function (appArg) {\n if (appArg === void 0) { appArg = app(); }\n if (typeof appArg[name] !== 'function') {\n // Invalid argument.\n // This happens in the following case: firebase.storage('gs:/')\n error('invalid-app-argument', { name: name });\n }\n // Forward service instance lookup to the FirebaseApp.\n return appArg[name]();\n };\n // ... and a container for service-level properties.\n if (serviceProperties !== undefined) {\n Object(cjs[\"deepExtend\"])(serviceNamespace, serviceProperties);\n }\n // Monkey-patch the serviceNamespace onto the firebase namespace\n namespace[name] = serviceNamespace;\n // Patch the FirebaseAppImpl prototype\n firebaseApp_FirebaseAppImpl.prototype[name] = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var serviceFxn = this._getService.bind(this, name);\n return serviceFxn.apply(this, allowMultipleInstances ? args : []);\n };\n return serviceNamespace;\n }\n /**\n * Patch the top-level firebase namespace with additional properties.\n *\n * firebase.INTERNAL.extendNamespace()\n */\n function extendNamespace(props) {\n Object(cjs[\"deepExtend\"])(namespace, props);\n }\n function callAppHooks(app, eventName) {\n Object.keys(factories).forEach(function (serviceName) {\n // Ignore virtual services\n var factoryName = useAsService(app, serviceName);\n if (factoryName === null) {\n return;\n }\n if (appHooks[factoryName]) {\n appHooks[factoryName](eventName, app);\n }\n });\n }\n // Map the requested service to a registered service name\n // (used to map auth to serverAuth service when needed).\n function useAsService(app, name) {\n if (name === 'serverAuth') {\n return null;\n }\n var useService = name;\n var options = app.options;\n return useService;\n }\n return namespace;\n}\nfunction error(code, args) {\n throw appErrors.create(code, args);\n}\n// TypeScript does not support non-string indexes!\n// let errors: {[code: AppError: string} = {\nvar errors = {\n 'no-app': \"No Firebase App '{$name}' has been created - \" +\n 'call Firebase App.initializeApp()',\n 'bad-app-name': \"Illegal App name: '{$name}\",\n 'duplicate-app': \"Firebase App named '{$name}' already exists\",\n 'app-deleted': \"Firebase App named '{$name}' already deleted\",\n 'duplicate-service': \"Firebase service named '{$name}' already registered\",\n 'sa-not-supported': 'Initializing the Firebase SDK with a service ' +\n 'account is only allowed in a Node.js environment. On client ' +\n 'devices, you should instead initialize the SDK with an api key and ' +\n 'auth domain',\n 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' +\n 'Firebase App instance.'\n};\nvar appErrors = new cjs[\"ErrorFactory\"]('app', 'Firebase', errors);\n\n\n//# sourceMappingURL=firebaseApp.js.map\n\n// CONCATENATED MODULE: ../app/dist/esm/index.js\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"firebase\", function() { return firebase; });\n/**\n * Copyright 2017 Google Inc.\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\nvar firebase = createFirebaseNamespace();\n/* harmony default export */ var esm = __webpack_exports__[\"default\"] = (firebase);\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 7 */,\n/* 8 */,\n/* 9 */,\n/* 10 */,\n/* 11 */,\n/* 12 */,\n/* 13 */,\n/* 14 */,\n/* 15 */,\n/* 16 */,\n/* 17 */,\n/* 18 */,\n/* 19 */\n/***/ (function(module, exports) {\n\nvar g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\nexports.CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n\n//# sourceMappingURL=constants.js.map\n\n\n/***/ }),\n/* 21 */,\n/* 22 */,\n/* 23 */,\n/* 24 */,\n/* 25 */,\n/* 26 */,\n/* 27 */\n/***/ (function(module, exports) {\n\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n/***/ }),\n/* 28 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar constants_1 = __webpack_require__(20);\n/**\n * Throws an error if the provided assertion is falsy\n * @param {*} assertion The assertion to be tested for falsiness\n * @param {!string} message The message to display if the check fails\n */\nexports.assert = function (assertion, message) {\n if (!assertion) {\n throw exports.assertionError(message);\n }\n};\n/**\n * Returns an Error object suitable for throwing.\n * @param {string} message\n * @return {!Error}\n */\nexports.assertionError = function (message) {\n return new Error('Firebase Database (' +\n constants_1.CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message);\n};\n\n//# sourceMappingURL=assert.js.map\n\n\n/***/ }),\n/* 29 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar stringToByteArray = function (str) {\n var output = [], p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n while (c > 255) {\n output[p++] = c & 255;\n c >>= 8;\n }\n output[p++] = c;\n }\n return output;\n};\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param {Array} bytes Array of numbers representing characters.\n * @return {string} Stringification of the array.\n */\nvar byteArrayToString = function (bytes) {\n var CHUNK_SIZE = 8192;\n // Special-case the simple case for speed's sake.\n if (bytes.length < CHUNK_SIZE) {\n return String.fromCharCode.apply(null, bytes);\n }\n // The remaining logic splits conversion by chunks since\n // Function#apply() has a maximum parameter count.\n // See discussion: http://goo.gl/LrWmZ9\n var str = '';\n for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {\n var chunk = bytes.slice(i, i + CHUNK_SIZE);\n str += String.fromCharCode.apply(null, chunk);\n }\n return str;\n};\n// Static lookup maps, lazily populated by init_()\nexports.base64 = {\n /**\n * Maps bytes to characters.\n * @type {Object}\n * @private\n */\n byteToCharMap_: null,\n /**\n * Maps characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMap_: null,\n /**\n * Maps bytes to websafe characters.\n * @type {Object}\n * @private\n */\n byteToCharMapWebSafe_: null,\n /**\n * Maps websafe characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMapWebSafe_: null,\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n * @type {string}\n */\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n * @type {string}\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n /**\n * Our websafe alphabet.\n * @type {string}\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n * @type {boolean}\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n /**\n * Base64-encode an array of bytes.\n *\n * @param {Array|Uint8Array} input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param {boolean=} opt_webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeByteArray: function (input, opt_webSafe) {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n this.init_();\n var byteToCharMap = opt_webSafe\n ? this.byteToCharMapWebSafe_\n : this.byteToCharMap_;\n var output = [];\n for (var i = 0; i < input.length; i += 3) {\n var byte1 = input[i];\n var haveByte2 = i + 1 < input.length;\n var byte2 = haveByte2 ? input[i + 1] : 0;\n var haveByte3 = i + 2 < input.length;\n var byte3 = haveByte3 ? input[i + 2] : 0;\n var outByte1 = byte1 >> 2;\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n var outByte4 = byte3 & 0x3f;\n if (!haveByte3) {\n outByte4 = 64;\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\n }\n return output.join('');\n },\n /**\n * Base64-encode a string.\n *\n * @param {string} input A string to encode.\n * @param {boolean=} opt_webSafe If true, we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeString: function (input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), opt_webSafe);\n },\n /**\n * Base64-decode a string.\n *\n * @param {string} input to decode.\n * @param {boolean=} opt_webSafe True if we should use the\n * alternative alphabet.\n * @return {string} string representing the decoded value.\n */\n decodeString: function (input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe));\n },\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param {string} input Input to decode.\n * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet.\n * @return {!Array} bytes representing the decoded value.\n */\n decodeStringToByteArray: function (input, opt_webSafe) {\n this.init_();\n var charToByteMap = opt_webSafe\n ? this.charToByteMapWebSafe_\n : this.charToByteMap_;\n var output = [];\n for (var i = 0; i < input.length;) {\n var byte1 = charToByteMap[input.charAt(i++)];\n var haveByte2 = i < input.length;\n var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n var haveByte3 = i < input.length;\n var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n var haveByte4 = i < input.length;\n var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n if (byte3 != 64) {\n var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n if (byte4 != 64) {\n var outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n return output;\n },\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_: function () {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n // We want quick mappings back and forth, so we precompute two maps.\n for (var i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n/**\n * URL-safe base64 encoding\n * @param {!string} str\n * @return {!string}\n */\nexports.base64Encode = function (str) {\n var utf8Bytes = stringToByteArray(str);\n return exports.base64.encodeByteArray(utf8Bytes, true);\n};\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param {string} str To be decoded\n * @return {?string} Decoded result, if possible\n */\nexports.base64Decode = function (str) {\n try {\n return exports.base64.decodeString(str, true);\n }\n catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n\n//# sourceMappingURL=crypt.js.map\n\n\n/***/ }),\n/* 30 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nfunction jsonEval(str) {\n return JSON.parse(str);\n}\nexports.jsonEval = jsonEval;\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nfunction stringify(data) {\n return JSON.stringify(data);\n}\nexports.stringify = stringify;\n\n//# sourceMappingURL=json.js.map\n\n\n/***/ }),\n/* 31 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/\nexports.contains = function (obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\nexports.safeGet = function (obj, key) {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key];\n // else return undefined.\n};\n/**\n * Enumerates the keys/values in an object, excluding keys defined on the prototype.\n *\n * @param {?Object.} obj Object to enumerate.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexports.forEach = function (obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n};\n/**\n * Copies all the (own) properties from one object to another.\n * @param {!Object} objTo\n * @param {!Object} objFrom\n * @return {!Object} objTo\n */\nexports.extend = function (objTo, objFrom) {\n exports.forEach(objFrom, function (key, value) {\n objTo[key] = value;\n });\n return objTo;\n};\n/**\n * Returns a clone of the specified object.\n * @param {!Object} obj\n * @return {!Object} cloned obj.\n */\nexports.clone = function (obj) {\n return exports.extend({}, obj);\n};\n/**\n * Returns true if obj has typeof \"object\" and is not null. Unlike goog.isObject(), does not return true\n * for functions.\n *\n * @param obj {*} A potential object.\n * @returns {boolean} True if it's an object.\n */\nexports.isNonNullObject = function (obj) {\n return typeof obj === 'object' && obj !== null;\n};\nexports.isEmpty = function (obj) {\n for (var key in obj) {\n return false;\n }\n return true;\n};\nexports.getCount = function (obj) {\n var rv = 0;\n for (var key in obj) {\n rv++;\n }\n return rv;\n};\nexports.map = function (obj, f, opt_obj) {\n var res = {};\n for (var key in obj) {\n res[key] = f.call(opt_obj, obj[key], key, obj);\n }\n return res;\n};\nexports.findKey = function (obj, fn, opt_this) {\n for (var key in obj) {\n if (fn.call(opt_this, obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n};\nexports.findValue = function (obj, fn, opt_this) {\n var key = exports.findKey(obj, fn, opt_this);\n return key && obj[key];\n};\nexports.getAnyKey = function (obj) {\n for (var key in obj) {\n return key;\n }\n};\nexports.getValues = function (obj) {\n var res = [];\n var i = 0;\n for (var key in obj) {\n res[i++] = obj[key];\n }\n return res;\n};\n/**\n * Tests whether every key/value pair in an object pass the test implemented\n * by the provided function\n *\n * @param {?Object.} obj Object to test.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexports.every = function (obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n if (!fn(key, obj[key])) {\n return false;\n }\n }\n }\n return true;\n};\n\n//# sourceMappingURL=obj.js.map\n\n\n/***/ }),\n/* 32 */,\n/* 33 */,\n/* 34 */,\n/* 35 */,\n/* 36 */,\n/* 37 */,\n/* 38 */,\n/* 39 */,\n/* 40 */,\n/* 41 */,\n/* 42 */,\n/* 43 */,\n/* 44 */,\n/* 45 */,\n/* 46 */,\n/* 47 */,\n/* 48 */,\n/* 49 */,\n/* 50 */,\n/* 51 */,\n/* 52 */,\n/* 53 */,\n/* 54 */,\n/* 55 */,\n/* 56 */,\n/* 57 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(58);\nmodule.exports = __webpack_require__(6).default;\n\n\n/***/ }),\n/* 58 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__ = __webpack_require__(59);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_shims_find__ = __webpack_require__(63);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_shims_find___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__src_shims_find__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_shims_findIndex__ = __webpack_require__(64);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_shims_findIndex___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__src_shims_findIndex__);\n/**\n * Copyright 2017 Google Inc.\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\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 59 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {/**\n * Copyright 2017 Google Inc.\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 */\nvar __global = (function () {\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n throw new Error('unable to locate global object');\n})();\n// Polyfill Promise\nif (typeof Promise === 'undefined') {\n // HACK: TS throws an error if I attempt to use 'dot-notation'\n __global['Promise'] = Promise = __webpack_require__(60);\n}\n\n//# sourceMappingURL=promise.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))\n\n/***/ }),\n/* 60 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(setImmediate) {(function (root) {\n\n // Store setTimeout reference so promise-polyfill will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var setTimeoutFunc = setTimeout;\n\n function noop() {}\n \n // Polyfill for Function.prototype.bind\n function bind(fn, thisArg) {\n return function () {\n fn.apply(thisArg, arguments);\n };\n }\n\n function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');\n if (typeof fn !== 'function') throw new TypeError('not a function');\n this._state = 0;\n this._handled = false;\n this._value = undefined;\n this._deferreds = [];\n\n doResolve(fn, this);\n }\n\n function handle(self, deferred) {\n while (self._state === 3) {\n self = self._value;\n }\n if (self._state === 0) {\n self._deferreds.push(deferred);\n return;\n }\n self._handled = true;\n Promise._immediateFn(function () {\n var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;\n if (cb === null) {\n (self._state === 1 ? resolve : reject)(deferred.promise, self._value);\n return;\n }\n var ret;\n try {\n ret = cb(self._value);\n } catch (e) {\n reject(deferred.promise, e);\n return;\n }\n resolve(deferred.promise, ret);\n });\n }\n\n function resolve(self, newValue) {\n try {\n // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');\n if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {\n var then = newValue.then;\n if (newValue instanceof Promise) {\n self._state = 3;\n self._value = newValue;\n finale(self);\n return;\n } else if (typeof then === 'function') {\n doResolve(bind(then, newValue), self);\n return;\n }\n }\n self._state = 1;\n self._value = newValue;\n finale(self);\n } catch (e) {\n reject(self, e);\n }\n }\n\n function reject(self, newValue) {\n self._state = 2;\n self._value = newValue;\n finale(self);\n }\n\n function finale(self) {\n if (self._state === 2 && self._deferreds.length === 0) {\n Promise._immediateFn(function() {\n if (!self._handled) {\n Promise._unhandledRejectionFn(self._value);\n }\n });\n }\n\n for (var i = 0, len = self._deferreds.length; i < len; i++) {\n handle(self, self._deferreds[i]);\n }\n self._deferreds = null;\n }\n\n function Handler(onFulfilled, onRejected, promise) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.promise = promise;\n }\n\n /**\n * Take a potentially misbehaving resolver function and make sure\n * onFulfilled and onRejected are only called once.\n *\n * Makes no guarantees about asynchrony.\n */\n function doResolve(fn, self) {\n var done = false;\n try {\n fn(function (value) {\n if (done) return;\n done = true;\n resolve(self, value);\n }, function (reason) {\n if (done) return;\n done = true;\n reject(self, reason);\n });\n } catch (ex) {\n if (done) return;\n done = true;\n reject(self, ex);\n }\n }\n\n Promise.prototype['catch'] = function (onRejected) {\n return this.then(null, onRejected);\n };\n\n Promise.prototype.then = function (onFulfilled, onRejected) {\n var prom = new (this.constructor)(noop);\n\n handle(this, new Handler(onFulfilled, onRejected, prom));\n return prom;\n };\n\n Promise.all = function (arr) {\n var args = Array.prototype.slice.call(arr);\n\n return new Promise(function (resolve, reject) {\n if (args.length === 0) return resolve([]);\n var remaining = args.length;\n\n function res(i, val) {\n try {\n if (val && (typeof val === 'object' || typeof val === 'function')) {\n var then = val.then;\n if (typeof then === 'function') {\n then.call(val, function (val) {\n res(i, val);\n }, reject);\n return;\n }\n }\n args[i] = val;\n if (--remaining === 0) {\n resolve(args);\n }\n } catch (ex) {\n reject(ex);\n }\n }\n\n for (var i = 0; i < args.length; i++) {\n res(i, args[i]);\n }\n });\n };\n\n Promise.resolve = function (value) {\n if (value && typeof value === 'object' && value.constructor === Promise) {\n return value;\n }\n\n return new Promise(function (resolve) {\n resolve(value);\n });\n };\n\n Promise.reject = function (value) {\n return new Promise(function (resolve, reject) {\n reject(value);\n });\n };\n\n Promise.race = function (values) {\n return new Promise(function (resolve, reject) {\n for (var i = 0, len = values.length; i < len; i++) {\n values[i].then(resolve, reject);\n }\n });\n };\n\n // Use polyfill for setImmediate for performance gains\n Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||\n function (fn) {\n setTimeoutFunc(fn, 0);\n };\n\n Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {\n if (typeof console !== 'undefined' && console) {\n console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console\n }\n };\n\n /**\n * Set the immediate function to execute callbacks\n * @param fn {function} Function to execute\n * @deprecated\n */\n Promise._setImmediateFn = function _setImmediateFn(fn) {\n Promise._immediateFn = fn;\n };\n\n /**\n * Change the function to execute on unhandled rejection\n * @param {function} fn Function to execute on unhandled rejection\n * @deprecated\n */\n Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {\n Promise._unhandledRejectionFn = fn;\n };\n \n if (typeof module !== 'undefined' && module.exports) {\n module.exports = Promise;\n } else if (!root.Promise) {\n root.Promise = Promise;\n }\n\n})(this);\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(61).setImmediate))\n\n/***/ }),\n/* 61 */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\n__webpack_require__(62);\nexports.setImmediate = setImmediate;\nexports.clearImmediate = clearImmediate;\n\n\n/***/ }),\n/* 62 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a ';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(25);\nvar Constants_1 = __webpack_require__(13);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(12);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(27)))\n\n/***/ }),\n/* 55 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar Node_1 = __webpack_require__(5);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 57 */,\n/* 58 */,\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = __webpack_require__(79);\n\n\n/***/ }),\n/* 79 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar Database_1 = __webpack_require__(32);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(36);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(21);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(26);\nvar INTERNAL = __webpack_require__(111);\nvar TEST_ACCESS = __webpack_require__(112);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(22);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(35);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Event_1 = __webpack_require__(85);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(87);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar ListenComplete_1 = __webpack_require__(88);\nvar Merge_1 = __webpack_require__(89);\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar SyncPoint_1 = __webpack_require__(47);\nvar WriteTree_1 = __webpack_require__(95);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar ViewProcessor_1 = __webpack_require__(91);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar CacheNode_1 = __webpack_require__(18);\nvar ViewCache_1 = __webpack_require__(48);\nvar EventGenerator_1 = __webpack_require__(94);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(8);\nvar Change_1 = __webpack_require__(9);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(92);\nvar Change_1 = __webpack_require__(9);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(10);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar CompleteChildSource_1 = __webpack_require__(93);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(18);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(5);\nvar Change_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar CompoundWrite_1 = __webpack_require__(96);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(49);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(53);\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(55);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ValueIndex_1 = __webpack_require__(38);\nvar PathIndex_1 = __webpack_require__(42);\nvar IndexedFilter_1 = __webpack_require__(24);\nvar LimitedFilter_1 = __webpack_require__(108);\nvar RangedFilter_1 = __webpack_require__(56);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(56);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(21);\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Path_1 = __webpack_require__(2);\nvar Tree_1 = __webpack_require__(110);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(43);\nvar validation_1 = __webpack_require__(7);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(11);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Repo_1 = __webpack_require__(17);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar BrowserPollConnection_1 = __webpack_require__(53);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(34);\nvar PersistentConnection_1 = __webpack_require__(50);\nvar RepoManager_1 = __webpack_require__(26);\nvar Connection_1 = __webpack_require__(52);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[78]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 2\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n __extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n __extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n !exports.isValidKey(parsedUrl.repoInfo.namespace) ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 7\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n __extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 11\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 12\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE\n .updateImmediateChild(childName, newChildNode)\n .updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n __extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 21\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 22\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.intializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return Promise.resolve();\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 32\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if (!namespace || namespace == 'undefined') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host and path.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n host = dataURL.substring(0, slashInd);\n pathString = decodePath(dataURL.substring(slashInd));\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 33\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost;\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n __extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n __extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n __extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 56\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 78\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 79\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 112\n// module chunks = 0","/*!\n * @license Firebase v4.6.1\n * Build: rev-0ea11f2\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([3],{\n\n/***/ 116:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(117);\n\n\n/***/ }),\n\n/***/ 117:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../util/dist/cjs/index.js\nvar cjs = __webpack_require__(0);\nvar cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/errors.js\n/**\n * Copyright 2017 Google Inc.\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\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\nvar ERROR_MAP = (_a = {},\n _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key must be a string with at ' + 'least one character.',\n _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n _a);\n/* harmony default export */ var errors = ({\n codes: CODES,\n map: ERROR_MAP\n});\nvar _a;\n\n//# sourceMappingURL=errors.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n/* harmony default export */ var array_buffer_to_base64 = (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n});;\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/fcm-details.js\n/**\n * Copyright 2017 Google Inc.\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\nvar FCM_APPLICATION_SERVER_KEY = [\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n];\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\n/* harmony default export */ var fcm_details = ({\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n});\n\n//# sourceMappingURL=fcm-details.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/token-manager.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar FCM_TOKEN_DETAILS_DB_VERSION = 1;\nvar token_manager_TokenManager = /** @class */ (function () {\n function TokenManager() {\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n this.openDbPromise_ = null;\n }\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n TokenManager.prototype.openDatabase_ = function () {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(TokenManager.DB_NAME, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n TokenManager.prototype.closeDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenManager.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getTokenDetailsFromSWScope_ = function (swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getAllTokenDetailsForSenderId_ = function (senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n }\n else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n };\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n TokenManager.prototype.subscribeToFCM = function (senderId, subscription, pushSet) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (pushSet) {\n fcmSubscribeBody += \"&pushSet=\" + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n TokenManager.prototype.isSameSubscription_ = function (subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (subscription.endpoint === masterTokenDetails['endpoint'] &&\n array_buffer_to_base64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n array_buffer_to_base64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']);\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n TokenManager.prototype.saveTokenDetails_ = function (senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: array_buffer_to_base64(subscription['getKey']('auth')),\n p256dh: array_buffer_to_base64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n TokenManager.prototype.getSavedToken = function (senderId, swRegistration) {\n var _this = this;\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return (swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']);\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n })\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager\n .getSubscription()\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.GET_SUBSCRIPTION_FAILED);\n })\n .then(function (subscription) {\n if (subscription &&\n _this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n };\n /**\n * Creates a new FCM token.\n */\n TokenManager.prototype.createToken = function (senderId, swRegistration) {\n var _this = this;\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager\n .getSubscription()\n .then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n })\n .then(function (sub) {\n subscription = sub;\n return _this.subscribeToFCM(senderId, subscription);\n })\n .then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n })\n .then(function () { return fcmTokenDetails['token']; });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenManager.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenManager;\n}());\n/* harmony default export */ var token_manager = (token_manager_TokenManager);\n\n//# sourceMappingURL=token-manager.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/notification-permission.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var notification_permission = ({\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n});\n\n//# sourceMappingURL=notification-permission.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/controller-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\nvar controller_interface_ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new token_manager();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete; };\n }\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== notification_permission.granted) {\n if (currentPermission === notification_permission.denied) {\n return Promise.reject(this.errorFactory_.create(errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this.tokenManager_\n .getSavedToken(_this.messagingSenderId_, registration)\n .then(function (token) {\n if (token) {\n return token;\n }\n return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);\n });\n });\n };\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return this.tokenManager_.closeDatabase();\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n /**\n * @protected\n * @returns {TokenManager}\n */\n ControllerInterface.prototype.getTokenManager = function () {\n return this.tokenManager_;\n };\n return ControllerInterface;\n}());\n/* harmony default export */ var controller_interface = (controller_interface_ControllerInterface);\n\n//# sourceMappingURL=controller-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/worker-page-message.js\n/**\n * Copyright 2017 Google Inc.\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// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\n/* harmony default export */ var worker_page_message = ({\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n});\n\n//# sourceMappingURL=worker-page-message.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/default-sw.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var default_sw = ({\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n});\n\n//# sourceMappingURL=default-sw.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/window-controller.js\n/**\n * Copyright 2017 Google Inc.\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\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\n\n\nvar window_controller_WindowController = /** @class */ (function (_super) {\n __extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n var _this = this;\n if (Notification.permission === notification_permission.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === notification_permission.granted) {\n return resolve();\n }\n else if (result === notification_permission.denied) {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(default_sw.path, {\n scope: default_sw.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n case worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[worker_page_message.PARAMS.DATA];\n _this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(controller_interface));\n/* harmony default export */ var window_controller = (window_controller_WindowController);\n\n//# sourceMappingURL=window-controller.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/sw-controller.js\n/**\n * Copyright 2017 Google Inc.\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\nvar sw_controller___extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n\n\n\n\nvar FCM_MSG = 'FCM_MSG';\nvar sw_controller_SWController = /** @class */ (function (_super) {\n sw_controller___extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this.errorFactory_.create(errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this.getTokenManager();\n return tokenManager\n .getTokenDetailsFromToken(token)\n .then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this.errorFactory_.create(errors.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n })\n .then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this.errorFactory_.create(errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this.errorFactory_.create(errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n return SWController;\n}(controller_interface));\n/* harmony default export */ var sw_controller = (sw_controller_SWController);\n\n//# sourceMappingURL=sw-controller.js.map\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(6);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerMessaging\"] = registerMessaging;\n/**\n * Copyright 2017 Google Inc.\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\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new sw_controller(app);\n }\n // Assume we are in the window context.\n return new window_controller(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: window_controller\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[116]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/messaging');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./messaging/index.js\n// module id = 116\n// module chunks = 3","/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\nexport default function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n};\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport WindowController from './src/controllers/window-controller';\nimport SWController from './src/controllers/sw-controller';\nimport firebase from '@firebase/app';\nexport function registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n // Assume we are in the window context.\n return new WindowController(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: WindowController\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\nvar ERROR_MAP = (_a = {},\n _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key must be a string with at ' + 'least one character.',\n _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n _a);\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\nvar _a;\n\n//# sourceMappingURL=errors.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/errors.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar FCM_APPLICATION_SERVER_KEY = [\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n];\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\nexport default {\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n};\n\n//# sourceMappingURL=fcm-details.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/fcm-details.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar FCM_TOKEN_DETAILS_DB_VERSION = 1;\nvar TokenManager = /** @class */ (function () {\n function TokenManager() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.openDbPromise_ = null;\n }\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n TokenManager.prototype.openDatabase_ = function () {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(TokenManager.DB_NAME, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n TokenManager.prototype.closeDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenManager.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getTokenDetailsFromSWScope_ = function (swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getAllTokenDetailsForSenderId_ = function (senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n }\n else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n };\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n TokenManager.prototype.subscribeToFCM = function (senderId, subscription, pushSet) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (pushSet) {\n fcmSubscribeBody += \"&pushSet=\" + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n TokenManager.prototype.isSameSubscription_ = function (subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (subscription.endpoint === masterTokenDetails['endpoint'] &&\n arrayBufferToBase64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n arrayBufferToBase64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']);\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n TokenManager.prototype.saveTokenDetails_ = function (senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: arrayBufferToBase64(subscription['getKey']('auth')),\n p256dh: arrayBufferToBase64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n TokenManager.prototype.getSavedToken = function (senderId, swRegistration) {\n var _this = this;\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return (swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']);\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n })\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager\n .getSubscription()\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.GET_SUBSCRIPTION_FAILED);\n })\n .then(function (subscription) {\n if (subscription &&\n _this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n };\n /**\n * Creates a new FCM token.\n */\n TokenManager.prototype.createToken = function (senderId, swRegistration) {\n var _this = this;\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager\n .getSubscription()\n .then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(function (sub) {\n subscription = sub;\n return _this.subscribeToFCM(senderId, subscription);\n })\n .then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n })\n .then(function () { return fcmTokenDetails['token']; });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenManager.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenManager;\n}());\nexport default TokenManager;\n\n//# sourceMappingURL=token-manager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/token-manager.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenManager from '../models/token-manager';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\nvar ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new TokenManager();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete; };\n }\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this.tokenManager_\n .getSavedToken(_this.messagingSenderId_, registration)\n .then(function (token) {\n if (token) {\n return token;\n }\n return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);\n });\n });\n };\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return this.tokenManager_.closeDatabase();\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n /**\n * @protected\n * @returns {TokenManager}\n */\n ControllerInterface.prototype.getTokenManager = function () {\n return this.tokenManager_;\n };\n return ControllerInterface;\n}());\nexport default ControllerInterface;\n\n//# sourceMappingURL=controller-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/controller-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\nexport default {\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n};\n\n//# sourceMappingURL=worker-page-message.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/worker-page-message.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n//# sourceMappingURL=default-sw.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/default-sw.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport { createSubscribe } from '@firebase/util';\nvar WindowController = /** @class */ (function (_super) {\n __extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(Errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n var _this = this;\n if (Notification.permission === NOTIFICATION_PERMISSION.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n }\n else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n _this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(ControllerInterface));\nexport default WindowController;\n\n//# sourceMappingURL=window-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/window-controller.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport FCMDetails from '../models/fcm-details';\nvar FCM_MSG = 'FCM_MSG';\nvar SWController = /** @class */ (function (_super) {\n __extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this.errorFactory_.create(Errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this.getTokenManager();\n return tokenManager\n .getTokenDetailsFromToken(token)\n .then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this.errorFactory_.create(Errors.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(FCMDetails.SUBSCRIPTION_OPTIONS);\n })\n .then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this.errorFactory_.create(Errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(Errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this.errorFactory_.create(Errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n return SWController;\n}(ControllerInterface));\nexport default SWController;\n\n//# sourceMappingURL=sw-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/sw-controller.js\n// module id = null\n// module chunks = ","/*!\n * @license Firebase v4.6.1\n * Build: rev-0ea11f2\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([2],{\n\n/***/ 118:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(119);\n\n\n/***/ }),\n\n/***/ 119:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(6);\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/constants.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nvar apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nvar apiUploadBaseUrl = '/v0';\nfunction setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nvar configOption = 'storageBucket';\n/**\n * 1 minute\n */\nvar shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nvar minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/error.js\n/**\n * Copyright 2017 Google Inc.\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\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\n\nvar errors = {};\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nfunction prependCode(code) {\n return 'storage/' + code;\n}\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nfunction bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nfunction projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nfunction invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nfunction error_canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nfunction invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nfunction noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/string.js\n/**\n * Copyright 2017 Google Inc.\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\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw unknown();\n}\nfunction utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nfunction percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar string_DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nfunction dataURLBytes_(string) {\n var parts = new string_DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nfunction dataURLContentType_(string) {\n var parts = new string_DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/taskenums.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/object.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/promise_external.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nfunction make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nfunction promise_external_resolve(value) {\n return Promise.resolve(value);\n}\nfunction promise_external_reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/type.js\n/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nfunction isDef(p) {\n return p != null;\n}\nfunction isJustDef(p) {\n return p !== void 0;\n}\nfunction isFunction(p) {\n return typeof p === 'function';\n}\nfunction isObject(p) {\n return typeof p === 'object';\n}\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio.js\n/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nvar ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode = ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio_network.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar xhrio_network_NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\n\n\n//# sourceMappingURL=xhrio_network.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhriopool.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Factory-like class for creating XhrIo instances.\n */\nvar xhriopool_XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new xhrio_network_NetworkXhrIo();\n };\n return XhrIoPool;\n}());\n\n\n//# sourceMappingURL=xhriopool.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/json.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nfunction jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/location.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\n/**\n * @struct\n */\nvar location_Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\n\n\n//# sourceMappingURL=location.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/path.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nfunction path_parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nfunction child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/url.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/metadata.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\n\nvar mappings_ = null;\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new location_Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/args.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n }\n else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar args_ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction metadataSpec(opt_optional) {\n return new args_ArgSpec(metadataValidator, opt_optional);\n}\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/fs.js\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nfunction getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/blob.js\n/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\n\n\n\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar blob_FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\n\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/array.js\n/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nfunction array_contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nfunction array_clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestinfo.js\nvar RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\n\n\n//# sourceMappingURL=requestinfo.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requests.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = blob_FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array_contains(allowed, status));\n return status;\n}\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nvar resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/observer.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * @struct\n */\nvar observer_Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) ||\n isDef(opt_error) ||\n isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\n\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/tasksnapshot.js\nvar UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\n\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/async.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nfunction async_async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promise_external_resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/task.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar task_UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = error_canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) ||\n isJustDef(p['error']) ||\n isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n var observer = new observer_Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n var typeOnly = !(isJustDef(nextOrObserver) ||\n isJustDef(error) ||\n isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = array_clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async_async(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async_async(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async_async(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async_async(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\n\n\n//# sourceMappingURL=task.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/reference.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar reference_Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof location_Location) {\n this.location = location;\n }\n else {\n this.location = location_Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path_parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new location_Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n validate('putString', [\n stringSpec(),\n stringSpec(formatValidator, true),\n metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (isDef(url)) {\n return url;\n }\n else {\n throw noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n return Reference;\n}());\n\n\n//# sourceMappingURL=reference.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/failrequest.js\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar failrequest_FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promise_external_reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\n\n\n//# sourceMappingURL=failrequest.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestmap.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * @struct\n */\nvar requestmap_RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\n\n\n//# sourceMappingURL=requestmap.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/authwrapper.js\n\n\n\n\n\n\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar authwrapper_AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new requestmap_RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = location_Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n isDef(this.app_.INTERNAL) &&\n isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promise_external_resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new failrequest_FailRequest(appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\n\n\n//# sourceMappingURL=authwrapper.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/backoff.js\n/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nfunction stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/request.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\n\n\n\n\n\n\n\n\n/**\n * @struct\n * @template T\n */\nvar request_NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array_contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? appDeleted()\n : error_canceled();\n reject(err);\n }\n else {\n var err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array_contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array_contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nfunction addVersionHeader_(headers) {\n var number = typeof esm[\"default\"] !== 'undefined' ? esm[\"default\"].SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new request_NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/service.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar service_Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new reference_Reference(authWrapper, loc);\n }\n this.authWrapper_ = new authwrapper_AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = location_Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new location_Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new service_ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n validate('ref', [stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new reference_Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n location_Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new reference_Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\n\n/**\n * @struct\n */\nvar service_ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return promise_external_resolve(undefined);\n };\n return ServiceInternals;\n}());\n\n\n//# sourceMappingURL=service.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerStorage\"] = registerStorage;\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new service_Service(app, new xhriopool_XhrIoPool(), opt_url);\n}\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: service_Service,\n Reference: reference_Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[118]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-storage.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-storage.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/storage');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./storage/index.js\n// module id = 118\n// module chunks = 2","/**\n * Copyright 2017 Google Inc.\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 */\nimport { configOption } from './constants';\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\nexport { FirebaseStorageError };\nexport var errors = {};\nexport var Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nexport function prependCode(code) {\n return 'storage/' + code;\n}\nexport function unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nexport function objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nexport function bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nexport function projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nexport function quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nexport function unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nexport function unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nexport function retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nexport function invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nexport function canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nexport function invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nexport function invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nexport function invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nexport function noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nexport function cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nexport function serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nexport function noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nexport function invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nexport function invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nexport function appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nexport var StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nexport function formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\nexport { StringData };\nexport function dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw errorsExports.unknown();\n}\nexport function utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nexport function percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nexport function base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nexport function dataURLBytes_(string) {\n var parts = new DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nexport function dataURLContentType_(string) {\n var parts = new DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/string.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport var TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nexport var InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nexport var TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nexport function taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/taskenums.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nexport function contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nexport function forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nexport function clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/object.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nexport function make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nexport function resolve(value) {\n return Promise.resolve(value);\n}\nexport function reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/promise_external.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef(p) {\n return p != null;\n}\nexport function isJustDef(p) {\n return p !== void 0;\n}\nexport function isFunction(p) {\n return typeof p === 'function';\n}\nexport function isObject(p) {\n return typeof p === 'object';\n}\nexport function isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nexport function isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nexport function isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nexport function isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nexport function isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nexport function isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/type.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/json.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nexport function child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport * as constants from './constants';\nimport * as object from './object';\nexport function makeNormalUrl(urlPart) {\n return constants.domainBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeDownloadUrl(urlPart) {\n return constants.downloadBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeUploadUrl(urlPart) {\n return constants.domainBase + constants.apiUploadBaseUrl + urlPart;\n}\nexport function makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n object.forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/url.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nexport function noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\nexport { Mapping };\nvar mappings_ = null;\nexport function xformPath(fullPath) {\n var valid = type.isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return path.lastComponent(fullPath);\n }\n}\nexport function getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (type.isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = type.isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = UrlUtils.makeDownloadUrl(urlPart);\n var queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nexport function addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nexport function fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nexport function fromResourceString(authWrapper, resourceString, mappings) {\n var obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nexport function toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nexport function metadataValidator(p) {\n var validType = p && type.isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/metadata.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as type from './type';\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n }\n else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\nexport { ArgSpec };\nexport function and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nexport function stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function metadataSpec(opt_optional) {\n return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);\n}\nexport function nonNegativeNumberSpec() {\n function validator(p) {\n var valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/args.js\n// module id = null\n// module chunks = ","import * as type from './type';\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (type.isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/fs.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nexport function contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nexport function clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nexport function remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/array.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as array from './array';\nimport { FbsBlob } from './blob';\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as object from './object';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn) {\n if (!cndn) {\n throw errorsExports.unknown();\n }\n}\nexport function metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = MetadataUtils.fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nexport function sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = errorsExports.unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = errorsExports.quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = errorsExports.unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = errorsExports.objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nexport function metadataForUpload_(location, blob, opt_metadata) {\n var metadata = object.clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nexport function multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = MetadataUtils.toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\nexport { ResumableUploadStatus };\nexport function checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array.contains(allowed, status));\n return status;\n}\nexport function createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport var resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw errorsExports.serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requests.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\nimport * as promiseimpl from './promise_external';\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promiseimpl.resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/async.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\nimport firebase from '@firebase/app';\nimport * as array from './array';\nimport * as backoff from './backoff';\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport * as XhrIoExports from './xhrio';\n/**\n * @struct\n * @template T\n */\nvar NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = promiseimpl.make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array.contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = errorsExports.unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? errorsExports.appDeleted()\n : errorsExports.canceled();\n reject(err);\n }\n else {\n var err = errorsExports.retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array.contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array.contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\nexport { RequestEndStatus };\nexport function addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nexport function addVersionHeader_(headers) {\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nexport function makeRequest(requestInfo, authToken, pool) {\n var queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = object.clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/request.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent } from './src/implementation/taskenums';\nimport { TaskState } from './src/implementation/taskenums';\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new Service(app, new XhrIoPool(), opt_url);\n}\nexport function registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode = ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nexport var domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nexport var downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nexport var apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nexport var apiUploadBaseUrl = '/v0';\nexport function setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nexport var configOption = 'storageBucket';\n/**\n * 1 minute\n */\nexport var shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nexport var defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nexport var defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport var minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/constants.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as XhrIoExports from './xhrio';\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = XhrIoExports.ErrorCode.NO_ERROR;\n this.sendPromise_ = promiseimpl.make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(opt_headers)) {\n var headers = opt_headers;\n object.forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (type.isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\nexport { NetworkXhrIo };\n\n//# sourceMappingURL=xhrio_network.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio_network.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { NetworkXhrIo } from './xhrio_network';\n/**\n * Factory-like class for creating XhrIo instances.\n */\nvar XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new NetworkXhrIo();\n };\n return XhrIoPool;\n}());\nexport { XhrIoPool };\n\n//# sourceMappingURL=xhriopool.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhriopool.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\n/**\n * @struct\n */\nvar Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\nexport { Location };\n\n//# sourceMappingURL=location.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/location.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport * as string from './string';\nimport { StringFormat } from './string';\nimport * as type from './type';\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (type.isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (type.isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (type.isString(val)) {\n return string.dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\nexport { FbsBlob };\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/blob.js\n// module id = null\n// module chunks = ","var RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\nexport { RequestInfo };\n\n//# sourceMappingURL=requestinfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestinfo.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * @struct\n */\nvar Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = type.isFunction(nextOrObserver) ||\n type.isDef(opt_error) ||\n type.isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\nexport { Observer };\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/observer.js\n// module id = null\n// module chunks = ","var UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\nexport { UploadTaskSnapshot };\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/tasksnapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\nimport { InternalTaskState } from './implementation/taskenums';\nimport { Observer } from './implementation/observer';\nimport { TaskEvent, TaskState } from './implementation/taskenums';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport * as fbsArgs from './implementation/args';\nimport * as fbsArray from './implementation/array';\nimport { async as fbsAsync } from './implementation/async';\nimport * as errors from './implementation/error';\nimport * as fbsPromiseimpl from './implementation/promise_external';\nimport * as fbsRequests from './implementation/requests';\nimport * as fbsTaskEnums from './implementation/taskenums';\nimport * as typeUtils from './implementation/type';\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = fbsPromiseimpl.make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new fbsRequests.ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = errors.canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = fbsArgs.nullFunctionSpec(true).validator;\n var observerValidator = fbsArgs.looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n fbsArgs.stringSpec(typeValidator),\n fbsArgs.looseObjectSpec(nextOrObserverValidator, true),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n fbsArgs.validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n fbsArgs.validate('on', specs, arguments);\n }\n var observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n fbsArgs.looseObjectSpec(binderNextOrObserverValidator),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n var typeOnly = !(typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n fbsArray.remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = fbsArray.clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n fbsAsync(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n fbsArgs.validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n fbsArgs.validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n fbsArgs.validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\nexport { UploadTask };\n\n//# sourceMappingURL=task.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/task.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport * as args from './implementation/args';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as object from './implementation/object';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport * as fbsString from './implementation/string';\nimport { StringFormat } from './implementation/string';\nimport * as type from './implementation/type';\nimport { UploadTask } from './task';\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof Location) {\n this.location = location;\n }\n else {\n this.location = Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n args.validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return metadata.getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n args.validate('child', [args.stringSpec()], arguments);\n var newPath = path.child(this.location.path, childPath);\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return path.lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n args.validate('put', [args.uploadDataSpec(), args.metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n args.validate('putString', [\n args.stringSpec(),\n args.stringSpec(fbsString.formatValidator, true),\n args.metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = fbsString.dataFromString(format, string);\n var metadata = object.clone(opt_metadata);\n if (!type.isDef(metadata['contentType']) && type.isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n args.validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n args.validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n args.validate('updateMetadata', [args.metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n args.validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (type.isDef(url)) {\n return url;\n }\n else {\n throw errorsExports.noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n };\n return Reference;\n}());\nexport { Reference };\n\n//# sourceMappingURL=reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/reference.js\n// module id = null\n// module chunks = ","import * as promiseimpl from './promise_external';\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promiseimpl.reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\nexport { FailRequest };\n\n//# sourceMappingURL=failrequest.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/failrequest.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as object from './object';\nimport * as constants from './constants';\n/**\n * @struct\n */\nvar RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = constants.minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n object.forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\nexport { RequestMap };\n\n//# sourceMappingURL=requestmap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestmap.js\n// module id = null\n// module chunks = ","import * as constants from './constants';\nimport * as errorsExports from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport * as promiseimpl from './promise_external';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = constants.defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[constants.configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n type.isDef(this.app_.INTERNAL) &&\n type.isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promiseimpl.resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new FailRequest(errorsExports.appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\nexport { AuthWrapper };\n\n//# sourceMappingURL=authwrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/authwrapper.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as fbsPromiseImpl from './implementation/promise_external';\nimport * as RequestExports from './implementation/request';\nimport { Reference } from './reference';\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(app, maker, RequestExports.makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n args.validate('setMaxUploadRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n args.validate('setMaxOperationRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\nexport { Service };\n/**\n * @struct\n */\nvar ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return fbsPromiseImpl.resolve(undefined);\n };\n return ServiceInternals;\n}());\nexport { ServiceInternals };\n\n//# sourceMappingURL=service.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/service.js\n// module id = null\n// module chunks = "]} \ No newline at end of file +{"version":3,"sources":["webpack:///firebase-app.js","webpack:///webpack/bootstrap 3f8caf4711e004e5b158","webpack:///util/dist/cjs/index.js","webpack:///tmp/tmp-208812ou3wR5n5ZCvd/node_modules/tslib/tslib.es6.js","webpack:///app/dist/esm/src/firebaseApp.js","webpack:///app/dist/esm/index.js","webpack:///(webpack)/buildin/global.js","webpack:///util/dist/cjs/src/constants.js","webpack:///tmp/tmp-208812ou3wR5n5ZCvd/node_modules/process/browser.js","webpack:///util/dist/cjs/src/assert.js","webpack:///util/dist/cjs/src/crypt.js","webpack:///util/dist/cjs/src/json.js","webpack:///util/dist/cjs/src/obj.js","webpack:///app/index.js","webpack:///polyfill/dist/esm/index.js","webpack:///polyfill/dist/esm/src/polyfills/promise.js","webpack:///polyfill/node_modules/promise-polyfill/lib/index.js","webpack:///tmp/tmp-208812ou3wR5n5ZCvd/node_modules/node-libs-browser/node_modules/timers-browserify/main.js","webpack:///tmp/tmp-208812ou3wR5n5ZCvd/node_modules/setimmediate/setImmediate.js","webpack:///polyfill/dist/esm/src/shims/Array.js","webpack:///polyfill/dist/esm/src/shims/String.js","webpack:///util/dist/cjs/src/deepCopy.js","webpack:///util/dist/cjs/src/deferred.js","webpack:///util/dist/cjs/src/environment.js","webpack:///util/dist/cjs/src/errors.js","webpack:///util/dist/cjs/src/jwt.js","webpack:///util/dist/cjs/src/query.js","webpack:///util/dist/cjs/src/sha1.js","webpack:///util/dist/cjs/src/hash.js","webpack:///util/dist/cjs/src/subscribe.js","webpack:///util/dist/cjs/src/validation.js","webpack:///util/dist/cjs/src/utf8.js","webpack:///firebase-auth.js","webpack:///auth/index.js","webpack:///auth/dist/auth.js","webpack:///firebase-database.js","webpack:///database/dist/cjs/src/core/util/util.js","webpack:///database/dist/cjs/src/core/util/Path.js","webpack:///database/dist/cjs/src/core/snap/indexes/PriorityIndex.js","webpack:///database/dist/cjs/src/core/snap/ChildrenNode.js","webpack:///database/dist/cjs/src/core/snap/Node.js","webpack:///database/dist/cjs/src/core/util/validation.js","webpack:///database/dist/cjs/src/core/operation/Operation.js","webpack:///database/dist/cjs/src/core/view/Change.js","webpack:///database/dist/cjs/src/core/snap/indexes/KeyIndex.js","webpack:///database/dist/cjs/src/core/snap/nodeFromJSON.js","webpack:///database/dist/cjs/src/core/storage/storage.js","webpack:///database/dist/cjs/src/realtime/Constants.js","webpack:///database/dist/cjs/src/core/snap/indexes/Index.js","webpack:///database/dist/cjs/src/core/snap/LeafNode.js","webpack:///database/dist/cjs/src/core/util/SortedMap.js","webpack:///database/dist/cjs/src/core/Repo.js","webpack:///database/dist/cjs/src/core/view/CacheNode.js","webpack:///logger/dist/esm/index.js","webpack:///logger/dist/esm/src/logger.js","webpack:///database/dist/cjs/src/api/Reference.js","webpack:///database/dist/cjs/src/api/DataSnapshot.js","webpack:///database/dist/cjs/src/core/util/ImmutableTree.js","webpack:///database/dist/cjs/src/core/view/filter/IndexedFilter.js","webpack:///database/dist/cjs/src/core/stats/StatsManager.js","webpack:///database/dist/cjs/src/core/RepoManager.js","webpack:///database/dist/cjs/src/api/Database.js","webpack:///database/dist/cjs/src/core/util/libs/parser.js","webpack:///database/dist/cjs/src/core/RepoInfo.js","webpack:///database/dist/cjs/src/api/onDisconnect.js","webpack:///database/dist/cjs/src/api/Query.js","webpack:///database/dist/cjs/src/core/snap/snap.js","webpack:///database/dist/cjs/src/core/snap/indexes/ValueIndex.js","webpack:///database/dist/cjs/src/core/snap/IndexMap.js","webpack:///database/dist/cjs/src/core/snap/childSet.js","webpack:///database/dist/cjs/src/core/snap/comparators.js","webpack:///database/dist/cjs/src/core/snap/indexes/PathIndex.js","webpack:///database/dist/cjs/src/core/util/ServerValues.js","webpack:///database/dist/cjs/src/core/SparseSnapshotTree.js","webpack:///database/dist/cjs/src/core/util/CountedSet.js","webpack:///database/dist/cjs/src/core/operation/Overwrite.js","webpack:///database/dist/cjs/src/core/SyncPoint.js","webpack:///database/dist/cjs/src/core/view/ViewCache.js","webpack:///database/dist/cjs/src/core/stats/StatsListener.js","webpack:///database/dist/cjs/src/core/PersistentConnection.js","webpack:///database/dist/cjs/src/core/util/EventEmitter.js","webpack:///database/dist/cjs/src/realtime/Connection.js","webpack:///database/dist/cjs/src/realtime/BrowserPollConnection.js","webpack:///database/dist/cjs/src/realtime/WebSocketConnection.js","webpack:///database/dist/cjs/src/core/ServerActions.js","webpack:///database/dist/cjs/src/core/view/filter/RangedFilter.js","webpack:///database/index.js","webpack:///database/dist/cjs/index.js","webpack:///database/dist/cjs/src/core/storage/DOMStorageWrapper.js","webpack:///database/dist/cjs/src/core/storage/MemoryStorage.js","webpack:///database/dist/cjs/src/api/TransactionResult.js","webpack:///database/dist/cjs/src/core/util/NextPushId.js","webpack:///database/dist/cjs/src/core/view/EventRegistration.js","webpack:///database/dist/cjs/src/core/view/Event.js","webpack:///database/dist/cjs/src/core/SyncTree.js","webpack:///database/dist/cjs/src/core/operation/AckUserWrite.js","webpack:///database/dist/cjs/src/core/operation/ListenComplete.js","webpack:///database/dist/cjs/src/core/operation/Merge.js","webpack:///database/dist/cjs/src/core/view/View.js","webpack:///database/dist/cjs/src/core/view/ViewProcessor.js","webpack:///database/dist/cjs/src/core/view/ChildChangeAccumulator.js","webpack:///database/dist/cjs/src/core/view/CompleteChildSource.js","webpack:///database/dist/cjs/src/core/view/EventGenerator.js","webpack:///database/dist/cjs/src/core/WriteTree.js","webpack:///database/dist/cjs/src/core/CompoundWrite.js","webpack:///database/dist/cjs/src/core/SnapshotHolder.js","webpack:///database/dist/cjs/src/core/AuthTokenProvider.js","webpack:///database/dist/cjs/src/core/stats/StatsCollection.js","webpack:///database/dist/cjs/src/core/stats/StatsReporter.js","webpack:///database/dist/cjs/src/core/view/EventQueue.js","webpack:///database/dist/cjs/src/core/util/VisibilityMonitor.js","webpack:///database/dist/cjs/src/core/util/OnlineMonitor.js","webpack:///database/dist/cjs/src/realtime/TransportManager.js","webpack:///database/dist/cjs/src/realtime/polling/PacketReceiver.js","webpack:///database/dist/cjs/src/core/ReadonlyRestClient.js","webpack:///database/dist/cjs/src/core/view/QueryParams.js","webpack:///database/dist/cjs/src/core/view/filter/LimitedFilter.js","webpack:///database/dist/cjs/src/core/Repo_transaction.js","webpack:///database/dist/cjs/src/core/util/Tree.js","webpack:///database/dist/cjs/src/api/internal.js","webpack:///database/dist/cjs/src/api/test_access.js","webpack:///firebase-messaging.js","webpack:///messaging/index.js","webpack:///messaging/dist/esm/src/helpers/array-buffer-to-base64.js","webpack:///messaging/dist/esm/src/models/clean-v1-undefined.js","webpack:///messaging/dist/esm/src/models/token-details-model.js","webpack:///messaging/dist/esm/index.js","webpack:///messaging/dist/esm/src/models/errors.js","webpack:///messaging/dist/esm/src/models/db-interface.js","webpack:///messaging/dist/esm/src/models/fcm-details.js","webpack:///messaging/dist/esm/src/models/iid-model.js","webpack:///messaging/dist/esm/src/models/vapid-details-model.js","webpack:///messaging/dist/esm/src/controllers/controller-interface.js","webpack:///messaging/dist/esm/src/models/worker-page-message.js","webpack:///messaging/dist/esm/src/models/default-sw.js","webpack:///messaging/dist/esm/src/helpers/base64-to-array-buffer.js","webpack:///messaging/dist/esm/src/controllers/window-controller.js","webpack:///messaging/dist/esm/src/controllers/sw-controller.js","webpack:///firebase-storage.js","webpack:///storage/index.js","webpack:///storage/dist/esm/src/implementation/error.js","webpack:///storage/dist/esm/src/implementation/string.js","webpack:///storage/dist/esm/src/implementation/taskenums.js","webpack:///storage/dist/esm/src/implementation/object.js","webpack:///storage/dist/esm/src/implementation/promise_external.js","webpack:///storage/dist/esm/src/implementation/type.js","webpack:///storage/dist/esm/src/implementation/json.js","webpack:///storage/dist/esm/src/implementation/path.js","webpack:///storage/dist/esm/src/implementation/url.js","webpack:///storage/dist/esm/src/implementation/metadata.js","webpack:///storage/dist/esm/src/implementation/args.js","webpack:///storage/dist/esm/src/implementation/fs.js","webpack:///storage/dist/esm/src/implementation/array.js","webpack:///storage/dist/esm/src/implementation/requests.js","webpack:///storage/dist/esm/src/implementation/async.js","webpack:///storage/dist/esm/src/implementation/backoff.js","webpack:///storage/dist/esm/src/implementation/request.js","webpack:///storage/dist/esm/index.js","webpack:///storage/dist/esm/src/implementation/xhrio.js","webpack:///storage/dist/esm/src/implementation/constants.js","webpack:///storage/dist/esm/src/implementation/xhrio_network.js","webpack:///storage/dist/esm/src/implementation/xhriopool.js","webpack:///storage/dist/esm/src/implementation/location.js","webpack:///storage/dist/esm/src/implementation/blob.js","webpack:///storage/dist/esm/src/implementation/requestinfo.js","webpack:///storage/dist/esm/src/implementation/observer.js","webpack:///storage/dist/esm/src/tasksnapshot.js","webpack:///storage/dist/esm/src/task.js","webpack:///storage/dist/esm/src/reference.js","webpack:///storage/dist/esm/src/implementation/failrequest.js","webpack:///storage/dist/esm/src/implementation/requestmap.js","webpack:///storage/dist/esm/src/implementation/authwrapper.js","webpack:///storage/dist/esm/src/service.js"],"names":["firebase","window","self","modules","__webpack_require__","moduleId","installedModules","exports","module","i","l","call","parentJsonpFunction","chunkIds","moreModules","executeModules","chunkId","result","resolves","length","installedChunks","push","Object","prototype","hasOwnProperty","shift","s","6","m","c","d","name","getter","o","defineProperty","configurable","enumerable","get","n","__esModule","object","property","p","oe","err","console","error","value","assert_1","assert","assertionError","crypt_1","base64","base64Decode","base64Encode","constants_1","CONSTANTS","deepCopy_1","deepCopy","deepExtend","patchProperty","deferred_1","Deferred","environment_1","getUA","isMobileCordova","isNodeSdk","isReactNative","errors_1","ErrorFactory","FirebaseError","patchCapture","json_1","jsonEval","stringify","jwt_1","decode","isAdmin","issuedAtTime","isValidFormat","isValidTimestamp","obj_1","clone","contains","every","extend","findKey","findValue","forEach","getAnyKey","getCount","getValues","isEmpty","isNonNullObject","map","safeGet","query_1","querystring","querystringDecode","sha1_1","Sha1","subscribe_1","async","createSubscribe","validation_1","errorPrefix","validateArgCount","validateCallback","validateContextObject","validateNamespace","utf8_1","stringLength","stringToByteArray","__webpack_exports__","__extends","b","__","this","constructor","extendStatics","create","__rest","e","t","indexOf","getOwnPropertySymbols","__decorate","decorators","target","key","desc","arguments","r","getOwnPropertyDescriptor","Reflect","decorate","__param","paramIndex","decorator","__metadata","metadataKey","metadataValue","metadata","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","step","next","rejected","done","then","apply","__generator","body","verb","v","op","f","TypeError","_","y","label","ops","pop","trys","g","sent","throw","return","Symbol","iterator","__exportStar","__values","__read","ar","__spread","concat","__await","__asyncGenerator","a","q","resume","settle","fulfill","asyncIterator","__asyncDelegator","__asyncValues","__makeTemplateObject","cooked","raw","__importStar","mod","k","default","__importDefault","__assign","setPrototypeOf","__proto__","Array","assign","createFirebaseNamespace","removeApp","callAppHooks","apps_","app","DEFAULT_ENTRY_NAME","initializeApp","options","undefined","firebaseApp_FirebaseAppImpl","namespace","getApps","keys","registerService","createService","serviceProperties","appHook","allowMultipleInstances","factories","appHooks","serviceNamespace","appArg","cjs","args","_i","_getService","bind","extendNamespace","props","eventName","serviceName","factoryName","useAsService","useService","apps","SDK_VERSION","INTERNAL","code","appErrors","obj","tokenListeners","FirebaseAppImpl","firebase_","isDeleted_","services_","name_","options_","getUid","getToken","addAuthTokenListener","callback","setTimeout","removeAuthTokenListener","filter","listener","checkDestroyed_","delete","_this","services","serviceKey","instanceKey","all","service","instanceIdentifier","instanceSpecifier","extendApp","log","errors","no-app","bad-app-name","duplicate-app","app-deleted","duplicate-service","sa-not-supported","invalid-app-argument","Function","eval","NODE_CLIENT","NODE_ADMIN","defaultSetTimout","Error","defaultClearTimeout","runTimeout","fun","cachedSetTimeout","runClearTimeout","marker","cachedClearTimeout","clearTimeout","cleanUpNextTick","draining","currentQueue","queue","queueIndex","drainQueue","timeout","len","run","Item","array","noop","process","nextTick","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","assertion","message","str","out","charCodeAt","byteArrayToString","bytes","pos","c1","String","fromCharCode","c2","c3","c4","u","join","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","opt_webSafe","isArray","init_","byteToCharMap","byteToCharMapWebSafe_","byteToCharMap_","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","decodeString","decodeStringToByteArray","charToByteMap","charToByteMapWebSafe_","charToByteMap_","charAt","haveByte4","byte4","O","utf8Bytes","JSON","parse","data","fn","objTo","objFrom","rv","opt_obj","res","opt_this","__WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__","__WEBPACK_IMPORTED_MODULE_1__src_shims_Array__","__WEBPACK_IMPORTED_MODULE_2__src_shims_String__","global","__global","setImmediate","_state","_handled","_value","_deferreds","doResolve","handle","deferred","_immediateFn","cb","onFulfilled","onRejected","promise","ret","newValue","finale","_unhandledRejectionFn","Handler","reason","ex","setTimeoutFunc","prom","arr","val","remaining","slice","race","values","warn","Timeout","id","clearFn","_id","_clearFn","setInterval","clearInterval","close","unref","ref","enroll","item","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","clearImmediate","task","tasksByHandle","nextHandle","registerImmediate","runIfPresent","currentlyRunningATask","doc","document","attachTo","getPrototypeOf","toString","postMessage","importScripts","postMessageIsAsynchronous","oldOnMessage","onmessage","messagePrefix","Math","random","onGlobalMessage","event","source","addEventListener","attachEvent","MessageChannel","channel","port1","port2","createElement","html","documentElement","script","onreadystatechange","removeChild","appendChild","find","predicate","kValue","findIndex","startsWith","search","substr","Date","dateValue","getTime","prop","wrapCallback","catch","navigator","test","captureFake","captureStackTrace","ERROR_NAME","err_1","stack","pattern","template","fullCode","replace","match","token","header","claims","signature","parts","split","validSince","validUntil","now","floor","decoded","querystringParams","params","arrayVal","encodeURIComponent","tslib_1","hash_1","_super","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","opt_offset","W","update","opt_length","lengthMinusBlock","inbuf","digest","totalBits","j","Hash","executor","onNoObservers","proxy","ObserverProxy","subscribe","onError","implementsAnyMethods","methods","methods_1","method","observers","unsubscribes","observerCount","finalized","forEachObserver","observer","complete","nextOrObserver","unsub","unsubscribeOne","finalError","sendOne","fnName","argumentNumber","optional","argName","context","minCount","maxCount","argCount","argError","high","webpackJsonpFirebase","78","79","ba","ca","da","splice","propertyIsEnumerable","ea","fa","ha","ka","la","unshift","ma","lb","$c","oa","$goog_Thenable","pa","qa","ra","sa","ta","ua","xa","ya","va","Aa","Da","Ea","Fa","za","Ga","Ha","Ia","Ja","Ka","Ma","Na","Oa","Pa","Qa","Ra","Sa","Ta","w","Ua","x","Va","Ya","Za","$a","bb","ab","eb","style","display","src","contentWindow","open","write","location","protocol","host","origin","rb","parentNode","fb","gb","hb","ib","add","jb","Window","db","wa","kb","h","mb","nb","ob","pb","qb","z","A","sb","tb","ub","vb","Zb","yb","zb","Ab","xb","Bb","wb","E","Jc","Kc","Cb","Db","Ub","Eb","Fb","Gb","Hb","Ib","ia","ja","Jb","Kb","Lb","Mb","Sb","documentMode","Xb","La","Tb","max","exec","parseInt","C","type","dc","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","Qb","nodeName","fromElement","toElement","pageX","pageY","ec","defaultPrevented","ic","capture","hc","jc","kc","mc","lc","qc","rc","sc","fc","tc","uc","vc","nc","wc","cc","xc","pc","yc","ac","zc","D","Ac","removeEventListener","detachEvent","oc","Bc","Cc","keyCode","returnValue","Dc","handleEvent","F","Ec","Fc","Gc","Ic","R","T","Lc","set","Mc","Nc","Pc","substring","decodeURIComponent","Qc","Rc","Sc","Tc","Uc","Oc","Vc","isNaN","ad","Wc","bd","G","cd","dd","ed","decodeURI","encodeURI","fd","gd","hd","kd","jd","ld","toLowerCase","nd","od","pd","qd","rd","sd","td","ud","vd","wd","xd","yd","zd","Ad","Cd","Bd","Dd","Ed","Fd","Gd","Hd","Id","getElementById","Jd","cssText","className","htmlFor","Kd","setAttribute","lastIndexOf","Ld","md","Md","createTextNode","nodeType","Nd","Od","Pd","Qd","Number","Boolean","Rd","valueOf","isFinite","Td","Sd","Ud","H","B","Yb","Vd","href","Wd","Xd","Yd","Zd","$d","ae","be","ce","screen","availHeight","availWidth","width","height","top","left","resizable","statusbar","toolbar","de","scrollbars","standalone","noreferrer","createEvent","initMouseEvent","dispatchEvent","Pb","opener","noopener","focus","ee","closed","ge","readyState","he","ie","je","ke","le","me","ne","pe","sort","userAgent","I","qe","localStorage","re","setItem","removeItem","indexedDB","se","te","ue","ve","we","xe","ye","ze","___jsl","L","CP","Ae","onLine","connection","Be","Ce","visibilityState","Ee","Fe","toUTCString","Ge","J","Ie","K","Ke","Le","Me","Ne","Oe","Pe","Qe","Re","Se","Te","Ue","Ve","We","Xe","Ye","Ze","$e","af","bf","cf","df","ef","ff","gf","hf","jf","continueUrl","canHandleCodeInApp","androidPackageName","androidMinimumVersion","androidInstallApp","iOSBundleId","kf","Ba","nf","of","mf","pf","lf","qf","sub","na","provider_id","sign_in_provider","is_anonymous","rf","iss","aud","exp","vf","uf","wf","xf","yf","zf","Af","Bf","Cf","Df","Ef","isNewUser","kind","rawUserInfo","providerId","profile","login","screenName","Ff","Gf","M","Hf","idToken","accessToken","oauthToken","oauthTokenSecret","Jf","id_token","access_token","secret","oauth_token_secret","postBody","requestUri","Mf","isOAuthProvider","Xa","N","tf","Nf","Of","credential","Pf","Qf","Rf","Sf","Tf","sf","Uf","Vf","EMAIL_LINK_SIGN_IN_METHOD","EMAIL_PASSWORD_SIGN_IN_METHOD","$f","ag","bg","Y","cg","temporaryProof","phoneNumber","sessionInfo","fg","auth","hg","ig","oauthAccessToken","oauthIdToken","jg","kg","lg","eventId","urlResponse","sessionId","mg","og","pg","qg","email","sg","tg","vg","wg","XMLHttpRequest","ActiveXObject","xg","yg","XDomainRequest","responseText","status","statusText","onload","onerror","onprogress","bc","ontimeout","zg","Ag","Cg","Dg","Ig","Lg","Kg","Jg","Gg","Q","Hg","Mg","Ng","Og","Headers","Pg","Qg","headers","Rg","Ug","toUpperCase","ug","Vg","Wg","FormData","Tg","setRequestHeader","responseType","withCredentials","Xg","Yg","send","abort","Zg","$g","ah","aa","bh","ch","Sg","Eg","dh","eh","hh","ih","gh","jh","kh","lh","mh","Ca","nh","oh","fh","ph","qh","rh","sh","th","uh","attributes","charset","vh","getElementsByTagName","tagName","wh","xh","secureTokenEndpoint","secureTokenTimeout","yh","secureTokenHeaders","zh","firebaseEndpoint","firebaseTimeout","Ah","firebaseHeaders","Bh","node","Dh","Eh","Fh","Ch","Gh","gapi","client","request","Ih","Hh","Jh","grant_type","refresh_token","Kh","Lh","Mh","rg","Nh","Oh","Ph","identifier","continueUri","allProviders","Qh","signinMethods","Rh","Sh","authorizedDomains","Th","Uh","gg","ai","ci","di","deleteProvider","ei","fi","needConfirmation","errorMessage","gi","If","returnIdpCredential","hi","Kf","ii","Lf","autoCreate","ji","ki","oobCode","S","returnSecureToken","endpoint","$","keyInvalid","ipRefererBlocked","INVALID_CUSTOM_TOKEN","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_EMAIL","INVALID_PASSWORD","USER_DISABLED","MISSING_PASSWORD","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","FEDERATED_USER_ID_ALREADY_LINKED","INVALID_MESSAGE_PAYLOAD","INVALID_RECIPIENT_EMAIL","INVALID_SENDER","EMAIL_NOT_FOUND","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","CORS_UNSUPPORTED","DYNAMIC_LINK_NOT_ACTIVATED","INVALID_APP_ID","TOO_MANY_ATTEMPTS_TRY_LATER","WEAK_PASSWORD","OPERATION_NOT_ALLOWED","USER_CANCELLED","CAPTCHA_CHECK_FAILED","INVALID_APP_CREDENTIAL","INVALID_CODE","INVALID_PHONE_NUMBER","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_APP_CREDENTIAL","MISSING_CODE","MISSING_PHONE_NUMBER","MISSING_SESSION_INFO","QUOTA_EXCEEDED","SESSION_EXPIRED","INVALID_CONTINUE_URI","MISSING_ANDROID_PACKAGE_NAME","MISSING_IOS_BUNDLE_ID","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","INVALID_CERT_HASH","ui","ti","wi","xi","yi","where","url","messageHandlersFilter","position","dontclear","restyle","setHideOnLeave","zi","ping","Ai","Bi","register","Ei","Di","Ci","Fi","Gi","Hi","Ii","Ji","fe","RegExp","Ki","Li","Ni","Oi","authEvent","Mi","webStorageSupport","Pi","reactNative","AsyncStorage","Qi","Ri","Ti","errorCode","onupgradeneeded","createObjectStore","keyPath","onsuccess","Ui","Vi","objectStore","Wi","transaction","Xi","Yi","cancel","Zi","$i","aj","bj","cj","dj","ej","sessionStorage","fj","Browser","gj","Node","hj","ReactNative","ij","Worker","jj","mj","lj","nj","kj","Si","pj","oj","qj","rj","sj","getItem","tj","X","uj","vj","oldValue","wj","yj","xj","zj","Aj","Bj","Cj","Uint8Array","Int32Array","Dj","Ej","Jj","gc","Hc","De","Kj","Lj","Mj","Nj","Oj","Pj","Qj","Ij","Sj","ibi","apn","appDisplayName","Uj","Rj","Vj","Tj","handleOpenURL","ng","Wj","Yj","Xj","Zj","ak","bk","ck","dk","unknown","signInViaRedirect","linkViaRedirect","reauthViaRedirect","signInViaPopup","linkViaPopup","reauthViaPopup","ek","vi","fk","gk","hk","ik","lk","nk","mk","ok","pk","qk","rk","user","sk","kk","tk","uk","vk","wk","yk","xk","stop","zk","Ak","refreshToken","Bk","expiresIn","Ck","expires_in","expirationTime","Dk","lastSignInTime","creationTime","Ek","Fk","uid","displayName","photoURL","Gk","Hk","apiKey","appName","authDomain","Ik","Jk","Kk","U","Lk","V","Mk","Nk","Ok","Pk","start","Qk","Rk","Sk","Tk","emailVerified","isAnonymous","createdAt","lastLoginAt","providerData","Uk","Vk","Wk","Xk","Yk","Zk","$k","al","bl","cl","qi","dl","providerUserInfo","rawId","photoUrl","fl","el","additionalUserInfo","operationType","gl","reload","hl","il","jl","Z","kl","ll","ml","ga","nl","stsTokenManager","redirectEventId","ol","pl","ql","rl","sl","tl","vl","wl","xl","ul","yl","zl","Al","Bl","Ob","Cl","Dl","El","Fl","logFramework","Gl","Hl","Il","Jl","Nb","Kl","Ll","Ml","Nl","currentUser","Pl","_lat","Ol","Ql","theme","Rl","Sl","hasChildNodes","Tl","Ul","Vl","Wl","Xl","$l","bm","grecaptcha","Infinity","Yl","render","am","Zl","cm","dm","em","fm","gm","hm","im","jm","Element","km","lm","App","mm","nm","om","verify","pm","qm","some","trim","Wa","Rb","Vb","Wb","parseFloat","compatMode","$b","freeze","2","3","4","preventDefault","clear","Xc","Yc","Zc","cellpadding","cellspacing","colspan","frameborder","maxlength","nonce","role","rowspan","usemap","valign","\"","\\","/","\b","\f","\n","\r","\t","\u000b","He","Je","abcd","toJSON","argument-error","app-not-authorized","app-not-installed","captcha-check-failed","code-expired","cordova-not-ready","cors-unsupported","credential-already-in-use","custom-token-mismatch","requires-recent-login","dynamic-link-not-activated","email-already-in-use","expired-action-code","cancelled-popup-request","internal-error","invalid-app-credential","invalid-app-id","invalid-user-token","invalid-auth-event","invalid-verification-code","invalid-continue-uri","invalid-cordova-configuration","invalid-custom-token","invalid-email","invalid-api-key","invalid-cert-hash","invalid-credential","invalid-persistence-type","invalid-message-payload","invalid-oauth-provider","invalid-oauth-client-id","unauthorized-domain","invalid-action-code","wrong-password","invalid-phone-number","invalid-recipient-email","invalid-sender","invalid-verification-id","missing-android-pkg-name","auth-domain-config-required","missing-app-credential","missing-verification-code","missing-continue-uri","missing-iframe-start","missing-ios-bundle-id","missing-phone-number","missing-verification-id","account-exists-with-different-credential","network-request-failed","no-auth-event","no-such-provider","operation-not-allowed","operation-not-supported-in-this-environment","popup-blocked","popup-closed-by-user","provider-already-linked","quota-exceeded","redirect-cancelled-by-user","redirect-operation-pending","user-token-expired","too-many-requests","unauthorized-continue-uri","unsupported-persistence-type","user-cancelled","user-not-found","user-disabled","user-mismatch","user-signed-out","weak-password","web-storage-unsupported","signInMethod","Wf","Xf","password","Yf","Zf","PROVIDER_ID","dg","operation","eg","verificationId","verificationCode","recaptchaToken","PHONE_SIGN_IN_METHOD","unsubscribe","getResponseHeader","contentType","getAllResponseHeaders","Bg","Fg","credentials","cache","fetch","Request","text","append","entries","getResponse","response","mozResponseArrayBuffer","Content-Type","setApiKey","setToken","path","authType","Vh","Wh","Xh","deleteAttribute","requestType","Yh","Zh","$h","bi","li","newPassword","mi","ni","oi","pi","ri","recaptchaSiteKey","si","put","fbase_key","getAll","openCursor","NONE","Fj","Gj","Hj","jk","confirm","users","localId","passwordHash","languages","language","userLanguage","execute","firstChild","Persistence","LOCAL","SESSION","Auth","User","util_1","util_2","util_3","util_4","util_5","util_6","storage_1","util_7","logger_1","logClient","Logger","LUIDGenerator","sha1","sha1Bytes","buildLogMessage_","var_args","logger","firstLog_","enableLogging","logger_","persistent","logLevel","LogLevel","VERBOSE","SessionStorage","remove","logWrapper","prefix","fatal","warnIfPageIsSecure","warnAboutUnsupportedMethod","methodName","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","called_1","wrappedFn_1","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","each","bindCallback","doubleToIEEE754String","ln","bits","abs","pow","min","LN2","round","reverse","hexByteString","hexByte","isChromeExtensionContentScript","isWindowsStoreApp","Windows","UI","errorForServerCode","query","INTEGER_REGEXP_","intVal","exceptionGuard","callUserCallback","beingCrawled","exportPropGetter","fnGet","setTimeoutNonBlocking","time","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","begin","parent","pieces","child","childPathObj","childPieces","relativePath","outerPath","innerPath","outer","inner","comparePaths","right","leftKeys","rightKeys","cmp","equals","other","ValidationPath","errorPrefix_","parts_","byteLength_","checkValid_","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","Index_1","Node_1","LeafNode_1","PriorityIndex","compare","aPriority","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","NamedNode","MIN","maxPost","LeafNode","makePost","indexValue","priorityNode","Index","PRIORITY_INDEX","EMPTY_NODE","SortedMap_1","snap_1","PriorityIndex_1","KeyIndex_1","IndexMap_1","comparators_1","ChildrenNode","children_","priorityNode_","indexMap_","lazyHash_","validatePriorityNode","SortedMap","NAME_COMPARATOR","IndexMap","Default","isLeafNode","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","front","hasChild","updateImmediateChild","newChildNode","namedNode","newChildren","newIndexMap","newPriority","removeFromIndexes","insert","addToIndexes","updateChild","newImmediateChild","numChildren","count","exportFormat","numKeys","maxKey","allIntegerKeys","forEachChild","childNode","hash","toHash_1","priorityHashText","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","Wrap","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","KEY_INDEX","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","KeyIndex","__EMPTY_NODE","__childrenNodeConstructor","Path_1","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","isValidPriority","priority","validateFirebaseDataArg","validateFirebaseData","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","repoInfo","validateCredential","cred","validateBoolean","bool","validateString","string","validateObject","validateObjectContainsKey","opt_type","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","Server","forServerTaggedQuery","Change","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","json","ChildrenNode_1","jsonLeaf","USE_HINZE","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","childSet_1","buildChildSet","NAME_ONLY_COMPARATOR","sortedChildSet","getCompare",".priority","DOMStorageWrapper_1","MemoryStorage_1","createStoragefor","domStorageName","domStorage","DOMStorageWrapper","MemoryStorage","PersistentStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","oldWrapped","newWrapped","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","hasNext","LLRBNode","color","RED","copy","reverseTraversal","min_","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues_1","nodeFromJSON_1","SparseSnapshotTree_1","SyncTree_1","SnapshotHolder_1","AuthTokenProvider_1","StatsManager_1","StatsReporter_1","StatsListener_1","EventQueue_1","PersistentConnection_1","ReadonlyRestClient_1","Database_1","Repo","repoInfo_","forceRestClient","dataUpdateCount","statsListener_","eventQueue_","EventQueue","nextWriteId_","interceptServerDataCallback_","onDisconnect_","SparseSnapshotTree","persistentConnection_","authTokenProvider","AuthTokenProvider","stats_","StatsManager","getCollection","server_","ReadonlyRestClient","onDataUpdate_","onConnectStatus_","authOverride","PersistentConnection","onServerInfoUpdate_","addTokenChangeListener","refreshAuthToken","statsReporter_","getOrCreateReporter","StatsReporter","transactions_init_","infoData_","SnapshotHolder","infoSyncTree_","SyncTree","startListening","tag","currentHashFn","onComplete","infoEvents","getNode","applyServerOverwrite","stopListening","updateInfo_","serverSyncTree_","listen","events","raiseEventsForChangedPath","unlisten","secure","serverTime","offsetNode","offset","generateServerValues","generateWithValues","timestamp","isMerge","taggedChildren","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","changedChildren","applyServerMerge","snap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","updates","updateSnapshot","getNextWriteId_","setWithPriority","newVal","log_","serverValues","newNodeUnresolved","resolveDeferredValueSnapshot","writeId","applyUserOverwrite","queueEvents","errorReason","success","clearEvents","ackUserWrite","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","merge","changedPath","resolvedOnDisconnectTree","resolveDeferredValueTree","forEachTree","Empty","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","eventRegistration","addEventRegistration","raiseEventsAtPath","removeEventCallbackForQuery","removeEventRegistration","interrupt","stats","showDelta","StatsListener","longestName","reduce","previousValue","currentValue","stat","statsIncrementCounter","metric","incrementCounter","includeStat","__database","Database","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","setLogLevel","level","instances","inst","defaultLogLevel","INFO","defaultLogHandler","instance","logType","toISOString","DEBUG","info","WARN","ERROR","_logLevel","_logHandler","debug","onDisconnect_1","TransactionResult_1","NextPushId_1","Query_1","Repo_1","QueryParams_1","SyncPoint_1","Reference","repo","QueryParams","DEFAULT","getKey","getParent","parentPath","getRoot","databaseProp","database","objectToMerge","newObjectToMerge","transactionUpdate","applyLocally","promiseComplete","committed","TransactionResult","startTransaction","setPriority","nextPushId","thennablePushRef","pushRef","onDisconnect","OnDisconnect","Query","__referenceConstructor","SyncPoint","DataSnapshot","ref_","index_","exportVal","exists","childPathString","childPath","childRef","hasChildren","getRef","emptyChildrenSingleton","EmptyChildren","ImmutableTree","children","fromObject","tree","childSnap","findRootMostMatchingPathAndValue","childExistingPathAndValue","findRootMostValueAndPath","subtree","childTree","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","Change_1","IndexedFilter","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","getIndex","StatsCollection_1","hashString","collections_","StatsCollection","creatorFunction","reporters_","parser_1","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","dbUrl","databaseFromApp","parseRepoInfo","createRepo","deleteRepo","appRepos","toURLString","Reference_1","RepoManager_1","repo_","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","_a","decodePath","pathStringDecoded","piece","decodeQuery","queryString","results","segment","kv","RepoInfo_1","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","RepoInfo","port","colonInd","slashInd","questionMarkInd","queryParams","Constants_1","persistenceKey","internalHost","needsQueryParam","isCustomHost","isCacheableHost","isDemoHost","updateHost","newHost","connectionURL","connURL","pairs","ValueIndex_1","PathIndex_1","EventRegistration_1","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","PathIndex","VALUE_INDEX","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","getQueryParams","cancelCallbackOrContext","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","ValueEventRegistration","ChildEventRegistration","valueCallback","userCallback","cancelOrContext","firstCall","onceCallback","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","ValueIndex","valueNode","_defaultIndexMap","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","SortedMap_2","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","middle","base12","root","buildPennant","chunkSize","attachPennant","pennant","isOne","indexPath_","extractChild","aChild","bChild","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","CountedSet_1","CountedSet","self_1","prefixPath","func","Operation_1","Overwrite","OVERWRITE","operationForChild","CacheNode_1","ViewCache_1","View_1","views_","applyOperation","writesCache","optCompleteServerCache","view","events_1","serverCache","serverCacheComplete","eventCache","calcCompleteEventCache","eventCacheComplete","calcCompleteEventChildren","viewCache","ViewCache","View","getInitialEvents","cancelError","removed","cancelEvents","hadCompleteView","hasCompleteView","viewQueryId","getQuery","loadsAllData","getQueryViews","getCompleteServerCache","viewForQuery","getCompleteView","viewExistsForQuery","eventCache_","serverCache_","updateEventSnap","eventSnap","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","collection_","last_","newStats","delta","app_1","VisibilityMonitor_1","OnlineMonitor_1","Connection_1","ServerActions_1","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","visible_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","VisibilityMonitor","onVisible_","OnlineMonitor","onOnline_","sendRequest","onResponse","curReqNum","msg","isDefault","listenSpec","hashFn","sendListen_","req","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","token_1","authMethod","requestData","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","reportStats","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","handleTimestamp_","sendConnectStats_","restoreState_","establishConnection_","visible","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage_1","onReady_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","forceRefresh","Connection","serverTimeOffset","normalizedPathString","statusCode","explanation","notifyForInvalidToken","queries","clientName","currentlyOnline","ServerActions","EventEmitter","allowedEvents_","listeners_","trigger","validateEventType_","eventData","getInitialEvent","et","TransportManager_1","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","TransportManager","start_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","onMessage","closeConnections_","PacketReceiver_1","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","BrowserPollConnection","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","PacketReceiver","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","incrementIncomingBytes_","sendNewPolls","closeAfter","pN","handleResponse","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","shutdown_","myDisconnFrame","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","iframeContents","iframe","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","rstate","setWebSocketImpl","impl","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","User-Agent","platform","mySock","onopen","onclose","handleIncomingFrame","isOldAndroid","oldAndroidRegex","oldAndroidMatch","previouslyFailed","isInMemoryStorage","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","resetKeepAlive","remainingData","sendString_","responsesRequiredToBeHealthy","healthyTimeout","IndexedFilter_1","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","startName","endName","registerDatabase","unused","TEST_ACCESS","DataSnapshot_1","domStorage_","prefix_","prefixedName_","storedVal","cache_","PUSH_CHARS","lastPushTime","lastRandChars","duplicateTime","timeStampChars","Event_1","callback_","cancelCallback_","context_","respondsTo","change","DataEvent","getEventRunner","ctx","getEventType","cancelCB_1","cb_1","createCancelEvent","CancelEvent","hasAnyCallback","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","thisKey","getPath","AckUserWrite_1","ImmutableTree_1","ListenComplete_1","Merge_1","Overwrite_1","WriteTree_1","listenProvider_","syncPointTree_","pendingWriteTree_","WriteTree","tagToQueryMap_","queryToTagMap_","newData","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","Merge","revert","getWrite","removeWrite","affectedTree_1","AckUserWrite","applyListenComplete","ListenComplete","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","applyTaggedOperation_","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","completeCache","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","createListenerForView_","queryForListening_","tagForQuery_","queryToRemove","tagToRemove","removeTags_","writeIdsToExclude","writeTree","maybeChildSyncPoint","childMap","views_1","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","affectedTree","ACK_USER_WRITE","LISTEN_COMPLETE","MERGE","ViewProcessor_1","EventGenerator_1","query_","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","ViewProcessor","initialServerCache","initialEventCache","newServerCache","newEventCache","viewCache_","eventGenerator_","EventGenerator","path_1","registration","maybeEvent","existing","completeServerCache","oldViewCache","assertIndexed","generateEventsForChanges_","changes","initialChanges","registrations","generateEventsForChanges","ChildChangeAccumulator_1","CompleteChildSource_1","ProcessorResult","filter_","newViewCache","filterServerNode","accumulator","ChildChangeAccumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","serverNode","completeChildren","completeEventChildren","completeNode","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","calcCompleteChild","changedSnap","oldServerSnap","serverFilter","newServerNode","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","getCompleteChild","newEventSnap","cacheHasChild_","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","changeMap_","oldChange","oldType","NoCompleteChildSource_","getChildAfterChild","writes_","optCompleteServerCache_","completeServerData","nodes","calcIndexedSlice","eventRegistrations","moves","generateEventsForType_","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","aWrapped","bWrapped","CompoundWrite_1","visibleWrites_","CompoundWrite","allWrites_","lastWriteId_","WriteTreeRef","addWrite","addWrites","record","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","getCompleteNode","treePath","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","shadowingNode","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","writeTree_","existingServerCache","rootmost","rootMostPath","newWrite","applySubtreeWrite_","priorityWrite_1","rootNode_","newSnapshotNode","app_","removeTokenChangeListener","counters_","amount","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","collection","statsToReport_","reportStats_","reportedStats","haveStatsToReport","eventLists_","recursionDepth_","eventDataList","currList","eventPath","EventList","raiseQueuedEventsMatchingPredicate_","sentAll","eventList","raise","events_","eventFn","EventEmitter_1","hidden","visibilityChange","online_","BrowserPollConnection_1","WebSocketConnection_1","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","this_1","toProcess","getListenId_","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","queryStringParameters","authTokenData","authToken","xhr","LimitedFilter_1","RangedFilter_1","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","isViewFromLeft","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","getLimit","copy_","newLimit","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","LimitedFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","rangedFilter_","reverse_","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","TransactionStatus","Tree_1","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","Tree","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","forEachAncestor","abortTransactionsOnNode_","forEachDescendant","lastSent","TreeNode","childCount","parent_","pathObj","updateParents_","includeSelf","childrenFirst","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef","120","121","toBase64","arrayBuffer","uint8Version","handleDb","objectStoreNames","OLD_OBJECT_STORE_NAME","iidModel","iid_model","openCursorRequest","cursor","tokenDetails","deleteToken","fcmSenderId","fcmToken","fcmPushSet","continue","deleteDatabase","OLD_DB_NAME","cleanV1","ValidateInput","registerMessaging","factoryMethod","sw_controller","window_controller","namespaceExports","Messaging","errors__a","tslib_es6","CODES","AVAILABLE_IN_WINDOW","AVAILABLE_IN_SW","SHOULD_BE_INHERITED","BAD_SENDER_ID","INCORRECT_GCM_SENDER_ID","PERMISSION_DEFAULT","PERMISSION_BLOCKED","UNSUPPORTED_BROWSER","NOTIFICATIONS_BLOCKED","FAILED_DEFAULT_REGISTRATION","SW_REGISTRATION_EXPECTED","GET_SUBSCRIPTION_FAILED","INVALID_SAVED_TOKEN","SW_REG_REDUNDANT","TOKEN_SUBSCRIBE_FAILED","TOKEN_SUBSCRIBE_NO_TOKEN","TOKEN_SUBSCRIBE_NO_PUSH_SET","TOKEN_UNSUBSCRIBE_FAILED","TOKEN_UPDATE_FAILED","TOKEN_UPDATE_NO_TOKEN","USE_SW_BEFORE_GET_TOKEN","INVALID_DELETE_TOKEN","DELETE_TOKEN_NOT_FOUND","DELETE_SCOPE_NOT_FOUND","BG_HANDLER_FUNCTION_EXPECTED","NO_WINDOW_CLIENT_TO_MSG","UNABLE_TO_RESUBSCRIBE","NO_FCM_TOKEN_FOR_RESUBSCRIBE","FAILED_TO_DELETE_TOKEN","NO_SW_IN_REG","BAD_SCOPE","BAD_VAPID_KEY","BAD_SUBSCRIPTION","BAD_TOKEN","BAD_PUSH_SET","FAILED_DELETE_VAPID_KEY","INVALID_PUBLIC_VAPID_KEY","USE_PUBLIC_KEY_BEFORE_GET_TOKEN","PUBLIC_KEY_DECRYPTION_FAILED","ERROR_MAP","codes","db_interface_DBInterface","DBInterface","dbName","dbVersion","errorFactory_","DB_NAME_","dbVersion_","openDbPromise_","TRANSACTION_READ_WRITE","openDatabase","onDBUpgrade","closeDatabase","db_interface","array_buffer_to_base64","DEFAULT_PUBLIC_VAPID_KEY","SUBSCRIPTION_DETAILS","userVisibleOnly","applicationServerKey","fcm_details","ENDPOINT","iid_model_IIDModel","IIDModel","senderId","subscription","publicVapidKey","p256dh","fcmSubscribeBody","subscribeOptions","fcmTokenResponse","pushSet","updateToken","fcmUpdateBody","updateFetchRes","updateOptions","fetchResponse","fcmUnsubscribeBody","unsubscribeOptions","DB_NAME","DB_VERSION","swScope","vapidKey","token_details_model_TokenDetailsModel","TokenDetailsModel","evt","oldVersion","createIndex","unique","validateInputs_","PushSubscription","getTokenDetailsFromToken","getTokenDetailsFromSWScope","scopeRequest","saveTokenDetails","details","createTime","token_details_model","vapid_details_model_DB_NAME","vapid_details_model_DB_VERSION","vapid_details_model_VapidDetailsModel","VapidDetailsModel","getVapidFromSWScope","saveVapidDetails","deleteVapidDetails","vapid_details_model","SENDER_ID_OPTION_NAME","controller_interface_ControllerInterface","ControllerInterface","messagingSenderId_","tokenDetailsModel_","vapidDetailsModel_","iidModel_","currentPermission","getNotificationPermission_","notification_permission","swReg","getSWRegistration_","reg","scope","manageExistingToken","getNewToken","isTokenStillValid","isValid","getPublicVapidKey_","publicKey","updatedToken","getPushSubscription_","pushSubscription","allDetails","iidTokenDetails","pushManager","getSubscription","requestPermission","useServiceWorker","usePublicVapidKey","b64PublicKey","optError","optCompleted","onTokenRefresh","setBackgroundMessageHandler","Notification","permission","getTokenDetailsModel","getVapidDetailsModel","getIIDModel","controller_interface","PARAMS","TYPE_OF_MSG","DATA","msgType","PUSH_MSG_RECEIVED","NOTIFICATION_CLICKED","createNewMsg","msgData","worker_page_message","TYPES_OF_MSG","default_sw","base64_to_array_buffer","base64String","padding","repeat","rawData","outputArray","window_controller_WindowController","WindowController","messageObserver_","tokenRefreshObserver_","onTokenRefresh_","registrationToUse_","manifestCheckPromise_","setupSWMessageListener_","isSupported_","manifestCheck_","manifestTag","querySelector","manifestContent","managePermissionResult","permissionPromise","ServiceWorkerRegistration","publicVapidKeyToUse_","parsedKey","waitForRegistrationToActivate_","serviceWorker","installing","waiting","state","stateChangeListener","browserErrorMessage","swRegistration","workerPageMessage","pushMessage","sw_controller_SWController","SWController","onPush_","onSubChange_","onNotificationClick_","bgMessageHandler_","msgPayload","handleMsgPromise","hasVisibleClients_","hasVisibleClients","notification","sendMessageToWindowClients_","notificationDetails","getNotificationData_","notificationTitle_1","showNotification","waitUntil","promiseChain","stopImmediatePropagation","clickAction","getWindowClient_","windowClient","clients","openWindow","internalMsg","attemptToMessageClient_","notificationInformation","URL","matchAll","includeUncontrolled","clientList","suitableClient","vapidKeyFromDatabase","esm","122","123","prependCode","FirebaseStorageError","Code","UNKNOWN","objectNotFound","OBJECT_NOT_FOUND","quotaExceeded","bucket","unauthenticated","UNAUTHENTICATED","unauthorized","UNAUTHORIZED","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","error_canceled","CANCELED","invalidUrl","INVALID_URL","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","cannotSliceBlob","CANNOT_SLICE_BLOB","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","noDownloadURL","NO_DOWNLOAD_URL","invalidArgument","INVALID_ARGUMENT","invalidArgumentCount","argMin","argMax","real","countPart","plural","INVALID_ARGUMENT_COUNT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","formatValidator","stringFormat","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","dataFromString","StringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","valid","lo","percentEncodedBytes_","hasMinus","hasUnder","invalidChar","hasPlus","hasSlash","string_DataURLParts","rest","endsWith","end","taskStateFromInternalTaskState","InternalTaskState","RUNNING","PAUSING","CANCELING","TaskState","PAUSED","SUCCESS","make","resolver","promise_external_resolve","promise_external_reject","isDef","isJustDef","isFunction","isObject","isNonArrayObject","isString","isNumber","isNativeBlob","isNativeBlobDefined","Blob","jsonObjectOrNull","path_parent","canonicalChildPath","component","lastComponent","makeNormalUrl","urlPart","domainBase","apiBaseUrl","makeDownloadUrl","downloadBase","makeUploadUrl","apiUploadBaseUrl","makeQueryString","encode","queryPart","nextPart","noXform_","xformPath","fullPath","getMappings","mappingsXformPath","xformSize","size","xformTokens","tokens","alt","mappings_","mappings","Mapping","nameMapping","xform","sizeMapping","addRef","authWrapper","generateRef","loc","location_Location","makeStorageReference","fromResource","resource","mapping","local","server","fromResourceString","resourceString","toResourceString","writable","metadataValidator","validate","specs","passed","minArgs","maxArgs","validator","and_","v1","v2","stringSpec","opt_validator","opt_optional","stringValidator","args_ArgSpec","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","sliceBlob","blob","webkitSlice","mozSlice","array_contains","elem","array_clone","arraylike","handlerCheck","cndn","metadataHandler","handler","sharedErrorHandler","errorHandler","newErr","getStatus","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","getMetadata","fullServerUrl","maxOperationRetryTime","requestInfo","RequestInfo","updateMetadata","deleteObject","successCodes","determineContentType_","metadataForUpload_","opt_metadata","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","metadataString","preBlobPart","postBlobPart","blob_FbsBlob","maxUploadRetryTime","uploadData","checkResumeHeader_","opt_allowed","createResumableUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","ResumableUploadStatus","continueResumableUpload","opt_status","opt_progressCallback","uploadStatus","newCurrent","current","bytesToUpload","total","bytesLeft","startByte","endByte","uploadCommand","X-Goog-Upload-Offset","progressCallback","async_async","argsToForward","canceled","cancelState","triggerCallback","triggeredCallback","callWithDelay","millis","timeoutId","hitTimeout","waitSeconds","waitMillis","wasTimeout","stopped","addAuthHeader_","addVersionHeader_","number","makeRequest","pool","request_NetworkRequest","additionalRetryCodes","factory","opt_url","service_Service","xhriopool_XhrIoPool","registerStorage","TaskEvent","Storage","reference_Reference","STORAGE_TYPE","ErrorCode","defaultMaxOperationRetryTime","defaultMaxUploadRetryTime","minSafeInteger","code_","message_","serverResponse_","codeProp","codeEquals","serverResponse","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","INVALID_CHECKSUM","INVALID_EVENT_NAME","NO_DEFAULT_BUCKET","opt_contentType","DataURLParts","STATE_CHANGED","xhrio_network_NetworkXhrIo","NetworkXhrIo","sent_","xhr_","errorCode_","NO_ERROR","sendPromise_","ABORT","NETWORK_ERROR","opt_body","opt_headers","getErrorCode","getResponseText","addUploadProgressListener","upload","removeUploadProgressListener","XhrIoPool","createXhrIo","Location","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","gsModify","httpModify","gsRegex","gsIndices","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","bucketValue","pathValue","opt_local","opt_writable","opt_xform","ArgSpec","FbsBlob","opt_elideCopy","blobType","data_","byteLength","size_","type_","realBlob","sliced","buffer","blobby","uint8Arrays","finalLength_1","merged_1","index_1","observer_Observer","Observer","opt_error","opt_complete","UploadTaskSnapshot","bytesTransferred","totalBytes","urls","task_UploadTask","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","getAuthToken","createRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","metadataRequest","multipartRequest","transferred","old","notifyObservers_","wasPaused","externalState","completed","typeValidator","_p","nextOrObserverValidator","nextValidator","observerValidator","nextOrObserverMessage","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","notifyObserver_","finishPromise_","triggered","pause","newRef","newPath","throwIfRoot_","putString","getDownloadURL","failrequest_FailRequest","FailRequest","appDelete","requestmap_RequestMap","RequestMap","map_","id_","addRequest","unmap","authwrapper_AuthWrapper","AuthWrapper","maker","requestMaker","bucket_","deleted_","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","_error","deleteApp","setMaxUploadRetryTime","setMaxOperationRetryTime","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","progressListener","progressEvent","lengthComputable","RequestEndStatus","hitServer","isRetryStatusCode_","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","Service","authWrapperBucket","internals_","service_ServiceInternals","ServiceInternals"],"mappings":";;;;;AAKA,GAAIA,UAAW,WACL,GAAIC,OAA2B,KAAXA,EAAyBC,KAAOD,CACtD,OAAgB,UAAUE,GCgClC,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAE,OAGA,IAAAC,GAAAF,EAAAD,IACAI,EAAAJ,EACAK,GAAA,EACAH,WAUA,OANAJ,GAAAE,GAAAM,KAAAH,EAAAD,QAAAC,IAAAD,QAAAH,GAGAI,EAAAE,GAAA,EAGAF,EAAAD,QA1DA,GAAAK,GAAAX,EAAA,oBACAA,GAAA,8BAAAY,EAAAC,EAAAC,GAIA,IADA,GAAAV,GAAAW,EAAAC,EAAAR,EAAA,EAAAS,KACQT,EAAAI,EAAAM,OAAoBV,IAC5BO,EAAAH,EAAAJ,GACAW,EAAAJ,IACAE,EAAAG,KAAAD,EAAAJ,GAAA,IAEAI,EAAAJ,GAAA,CAEA,KAAAX,IAAAS,GACAQ,OAAAC,UAAAC,eAAAb,KAAAG,EAAAT,KACAF,EAAAE,GAAAS,EAAAT,GAIA,KADAO,KAAAC,EAAAC,EAAAC,GACAG,EAAAC,QACAD,EAAAO,SAEA,IAAAV,EACA,IAAAN,EAAA,EAAYA,EAAAM,EAAAI,OAA2BV,IACvCQ,EAAAb,IAAAsB,EAAAX,EA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A,MAAAgF,MAAA29F,IAEA5iG,YAAA,EACAD,cAAA,IAEAb,OAAAY,eAAAq8H,EAAAh9H,UAAA,YACAc,IAAA,WACA,MAAAgF,MAAAo3H,IAEAr8H,YAAA,EACAD,cAAA,IAEAo8H,KAMAG,GAAA,WACA,QAAAC,GAAA/tH,GACAvJ,KAAAw0H,GAAAjrH,EAUA,MAJA+tH,GAAAp9H,UAAA+O,OAAA,WAEA,MADAjJ,MAAAw0H,GAAA5E,EAAAkF,YACAnW,MAAA14G,KAEAqxH,If7IA13H,GAAA,gBAAA6pH,EAyBA,IAAAI,IAAA,SAiBAJ,IAAAhQ,GAAA,YnBmoHG,MACO,MAAMh+G,GACN,KAAUgP,OACR","file":"firebase.js","sourcesContent":["/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\nvar firebase = (function() {\n var window = typeof window === 'undefined' ? self : window;\n return /******/ (function(modules) { // webpackBootstrap\n/******/ \t// install a JSONP callback for chunk loading\n/******/ \tvar parentJsonpFunction = window[\"webpackJsonpFirebase\"];\n/******/ \twindow[\"webpackJsonpFirebase\"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {\n/******/ \t\t// add \"moreModules\" to the modules object,\n/******/ \t\t// then flag all \"chunkIds\" as loaded and fire callback\n/******/ \t\tvar moduleId, chunkId, i = 0, resolves = [], result;\n/******/ \t\tfor(;i < chunkIds.length; i++) {\n/******/ \t\t\tchunkId = chunkIds[i];\n/******/ \t\t\tif(installedChunks[chunkId]) {\n/******/ \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n/******/ \t\t\t}\n/******/ \t\t\tinstalledChunks[chunkId] = 0;\n/******/ \t\t}\n/******/ \t\tfor(moduleId in moreModules) {\n/******/ \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n/******/ \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\tif(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);\n/******/ \t\twhile(resolves.length) {\n/******/ \t\t\tresolves.shift()();\n/******/ \t\t}\n/******/ \t\tif(executeModules) {\n/******/ \t\t\tfor(i=0; i < executeModules.length; i++) {\n/******/ \t\t\t\tresult = __webpack_require__(__webpack_require__.s = executeModules[i]);\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\treturn result;\n/******/ \t};\n/******/\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// objects to store loaded and loading chunks\n/******/ \tvar installedChunks = {\n/******/ \t\t6: 0\n/******/ \t};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// on error function for async loading\n/******/ \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = 59);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar assert_1 = __webpack_require__(30);\nexports.assert = assert_1.assert;\nexports.assertionError = assert_1.assertionError;\nvar crypt_1 = __webpack_require__(31);\nexports.base64 = crypt_1.base64;\nexports.base64Decode = crypt_1.base64Decode;\nexports.base64Encode = crypt_1.base64Encode;\nvar constants_1 = __webpack_require__(21);\nexports.CONSTANTS = constants_1.CONSTANTS;\nvar deepCopy_1 = __webpack_require__(67);\nexports.deepCopy = deepCopy_1.deepCopy;\nexports.deepExtend = deepCopy_1.deepExtend;\nexports.patchProperty = deepCopy_1.patchProperty;\nvar deferred_1 = __webpack_require__(68);\nexports.Deferred = deferred_1.Deferred;\nvar environment_1 = __webpack_require__(69);\nexports.getUA = environment_1.getUA;\nexports.isMobileCordova = environment_1.isMobileCordova;\nexports.isNodeSdk = environment_1.isNodeSdk;\nexports.isReactNative = environment_1.isReactNative;\nvar errors_1 = __webpack_require__(70);\nexports.ErrorFactory = errors_1.ErrorFactory;\nexports.FirebaseError = errors_1.FirebaseError;\nexports.patchCapture = errors_1.patchCapture;\nvar json_1 = __webpack_require__(32);\nexports.jsonEval = json_1.jsonEval;\nexports.stringify = json_1.stringify;\nvar jwt_1 = __webpack_require__(71);\nexports.decode = jwt_1.decode;\nexports.isAdmin = jwt_1.isAdmin;\nexports.issuedAtTime = jwt_1.issuedAtTime;\nexports.isValidFormat = jwt_1.isValidFormat;\nexports.isValidTimestamp = jwt_1.isValidTimestamp;\nvar obj_1 = __webpack_require__(33);\nexports.clone = obj_1.clone;\nexports.contains = obj_1.contains;\nexports.every = obj_1.every;\nexports.extend = obj_1.extend;\nexports.findKey = obj_1.findKey;\nexports.findValue = obj_1.findValue;\nexports.forEach = obj_1.forEach;\nexports.getAnyKey = obj_1.getAnyKey;\nexports.getCount = obj_1.getCount;\nexports.getValues = obj_1.getValues;\nexports.isEmpty = obj_1.isEmpty;\nexports.isNonNullObject = obj_1.isNonNullObject;\nexports.map = obj_1.map;\nexports.safeGet = obj_1.safeGet;\nvar query_1 = __webpack_require__(72);\nexports.querystring = query_1.querystring;\nexports.querystringDecode = query_1.querystringDecode;\nvar sha1_1 = __webpack_require__(73);\nexports.Sha1 = sha1_1.Sha1;\nvar subscribe_1 = __webpack_require__(75);\nexports.async = subscribe_1.async;\nexports.createSubscribe = subscribe_1.createSubscribe;\nvar validation_1 = __webpack_require__(76);\nexports.errorPrefix = validation_1.errorPrefix;\nexports.validateArgCount = validation_1.validateArgCount;\nexports.validateCallback = validation_1.validateCallback;\nexports.validateContextObject = validation_1.validateContextObject;\nexports.validateNamespace = validation_1.validateNamespace;\nvar utf8_1 = __webpack_require__(77);\nexports.stringLength = utf8_1.stringLength;\nexports.stringToByteArray = utf8_1.stringToByteArray;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 1 */,\n/* 2 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony export (immutable) */ __webpack_exports__[\"__extends\"] = __extends;\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__assign\", function() { return __assign; });\n/* harmony export (immutable) */ __webpack_exports__[\"__rest\"] = __rest;\n/* harmony export (immutable) */ __webpack_exports__[\"__decorate\"] = __decorate;\n/* harmony export (immutable) */ __webpack_exports__[\"__param\"] = __param;\n/* harmony export (immutable) */ __webpack_exports__[\"__metadata\"] = __metadata;\n/* harmony export (immutable) */ __webpack_exports__[\"__awaiter\"] = __awaiter;\n/* harmony export (immutable) */ __webpack_exports__[\"__generator\"] = __generator;\n/* harmony export (immutable) */ __webpack_exports__[\"__exportStar\"] = __exportStar;\n/* harmony export (immutable) */ __webpack_exports__[\"__values\"] = __values;\n/* harmony export (immutable) */ __webpack_exports__[\"__read\"] = __read;\n/* harmony export (immutable) */ __webpack_exports__[\"__spread\"] = __spread;\n/* harmony export (immutable) */ __webpack_exports__[\"__await\"] = __await;\n/* harmony export (immutable) */ __webpack_exports__[\"__asyncGenerator\"] = __asyncGenerator;\n/* harmony export (immutable) */ __webpack_exports__[\"__asyncDelegator\"] = __asyncDelegator;\n/* harmony export (immutable) */ __webpack_exports__[\"__asyncValues\"] = __asyncValues;\n/* harmony export (immutable) */ __webpack_exports__[\"__makeTemplateObject\"] = __makeTemplateObject;\n/* harmony export (immutable) */ __webpack_exports__[\"__importStar\"] = __importStar;\n/* harmony export (immutable) */ __webpack_exports__[\"__importDefault\"] = __importDefault;\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar 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 (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nfunction __extends(d, b) {\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\nvar __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\r\nfunction __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++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nfunction __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\nfunction __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nfunction __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __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 (_) try {\r\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, 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\nfunction __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nfunction __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n 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}\r\n\r\nfunction __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\nfunction __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\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nfunction __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\nfunction __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) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\r\n}\r\n\r\nfunction __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\r\n}\r\n\r\nfunction __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\nfunction __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 (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nfunction __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\n\n/***/ }),\n/* 3 */,\n/* 4 */,\n/* 5 */,\n/* 6 */,\n/* 7 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../util/dist/cjs/index.js\nvar cjs = __webpack_require__(0);\nvar cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);\n\n// CONCATENATED MODULE: ../app/dist/esm/src/firebaseApp.js\n/**\n * Copyright 2017 Google Inc.\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\nvar contains = function (obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\nvar DEFAULT_ENTRY_NAME = '[DEFAULT]';\n// An array to capture listeners before the true auth functions\n// exist\nvar tokenListeners = [];\n/**\n * Global context object for a collection of services using\n * a shared authentication state.\n */\nvar firebaseApp_FirebaseAppImpl = /** @class */ (function () {\n function FirebaseAppImpl(options, name, firebase_) {\n this.firebase_ = firebase_;\n this.isDeleted_ = false;\n this.services_ = {};\n this.name_ = name;\n this.options_ = Object(cjs[\"deepCopy\"])(options);\n this.INTERNAL = {\n getUid: function () { return null; },\n getToken: function () { return Promise.resolve(null); },\n addAuthTokenListener: function (callback) {\n tokenListeners.push(callback);\n // Make sure callback is called, asynchronously, in the absence of the auth module\n setTimeout(function () { return callback(null); }, 0);\n },\n removeAuthTokenListener: function (callback) {\n tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; });\n }\n };\n }\n Object.defineProperty(FirebaseAppImpl.prototype, \"name\", {\n get: function () {\n this.checkDestroyed_();\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseAppImpl.prototype, \"options\", {\n get: function () {\n this.checkDestroyed_();\n return this.options_;\n },\n enumerable: true,\n configurable: true\n });\n FirebaseAppImpl.prototype.delete = function () {\n var _this = this;\n return new Promise(function (resolve) {\n _this.checkDestroyed_();\n resolve();\n })\n .then(function () {\n _this.firebase_.INTERNAL.removeApp(_this.name_);\n var services = [];\n Object.keys(_this.services_).forEach(function (serviceKey) {\n Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) {\n services.push(_this.services_[serviceKey][instanceKey]);\n });\n });\n return Promise.all(services.map(function (service) {\n return service.INTERNAL.delete();\n }));\n })\n .then(function () {\n _this.isDeleted_ = true;\n _this.services_ = {};\n });\n };\n /**\n * Return a service instance associated with this app (creating it\n * on demand), identified by the passed instanceIdentifier.\n *\n * NOTE: Currently storage is the only one that is leveraging this\n * functionality. They invoke it by calling:\n *\n * ```javascript\n * firebase.app().storage('STORAGE BUCKET ID')\n * ```\n *\n * The service name is passed to this already\n * @internal\n */\n FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) {\n if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; }\n this.checkDestroyed_();\n if (!this.services_[name]) {\n this.services_[name] = {};\n }\n if (!this.services_[name][instanceIdentifier]) {\n /**\n * If a custom instance has been defined (i.e. not '[DEFAULT]')\n * then we will pass that instance on, otherwise we pass `null`\n */\n var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME\n ? instanceIdentifier\n : undefined;\n var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier);\n this.services_[name][instanceIdentifier] = service;\n }\n return this.services_[name][instanceIdentifier];\n };\n /**\n * Callback function used to extend an App instance at the time\n * of service instance creation.\n */\n FirebaseAppImpl.prototype.extendApp = function (props) {\n var _this = this;\n // Copy the object onto the FirebaseAppImpl prototype\n Object(cjs[\"deepExtend\"])(this, props);\n /**\n * If the app has overwritten the addAuthTokenListener stub, forward\n * the active token listeners on to the true fxn.\n *\n * TODO: This function is required due to our current module\n * structure. Once we are able to rely strictly upon a single module\n * implementation, this code should be refactored and Auth should\n * provide these stubs and the upgrade logic\n */\n if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) {\n tokenListeners.forEach(function (listener) {\n _this.INTERNAL.addAuthTokenListener(listener);\n });\n tokenListeners = [];\n }\n };\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n FirebaseAppImpl.prototype.checkDestroyed_ = function () {\n if (this.isDeleted_) {\n error('app-deleted', { name: this.name_ });\n }\n };\n return FirebaseAppImpl;\n}());\n// Prevent dead-code elimination of these methods w/o invalid property\n// copying.\n(firebaseApp_FirebaseAppImpl.prototype.name && firebaseApp_FirebaseAppImpl.prototype.options) ||\n firebaseApp_FirebaseAppImpl.prototype.delete ||\n console.log('dc');\n/**\n * Return a firebase namespace object.\n *\n * In production, this will be called exactly once and the result\n * assigned to the 'firebase' global. It may be called multiple times\n * in unit tests.\n */\nfunction createFirebaseNamespace() {\n var apps_ = {};\n var factories = {};\n var appHooks = {};\n // A namespace is a plain JavaScript Object.\n var namespace = {\n // Hack to prevent Babel from modifying the object returned\n // as the firebase namespace.\n __esModule: true,\n initializeApp: initializeApp,\n app: app,\n apps: null,\n Promise: Promise,\n SDK_VERSION: '4.12.0',\n INTERNAL: {\n registerService: registerService,\n createFirebaseNamespace: createFirebaseNamespace,\n extendNamespace: extendNamespace,\n createSubscribe: cjs[\"createSubscribe\"],\n ErrorFactory: cjs[\"ErrorFactory\"],\n removeApp: removeApp,\n factories: factories,\n useAsService: useAsService,\n Promise: Promise,\n deepExtend: cjs[\"deepExtend\"]\n }\n };\n // Inject a circular default export to allow Babel users who were previously\n // using:\n //\n // import firebase from 'firebase';\n // which becomes: var firebase = require('firebase').default;\n //\n // instead of\n //\n // import * as firebase from 'firebase';\n // which becomes: var firebase = require('firebase');\n Object(cjs[\"patchProperty\"])(namespace, 'default', namespace);\n // firebase.apps is a read-only getter.\n Object.defineProperty(namespace, 'apps', {\n get: getApps\n });\n /**\n * Called by App.delete() - but before any services associated with the App\n * are deleted.\n */\n function removeApp(name) {\n var app = apps_[name];\n callAppHooks(app, 'delete');\n delete apps_[name];\n }\n /**\n * Get the App object for a given name (or DEFAULT).\n */\n function app(name) {\n name = name || DEFAULT_ENTRY_NAME;\n if (!contains(apps_, name)) {\n error('no-app', { name: name });\n }\n return apps_[name];\n }\n Object(cjs[\"patchProperty\"])(app, 'App', firebaseApp_FirebaseAppImpl);\n /**\n * Create a new App instance (name must be unique).\n */\n function initializeApp(options, name) {\n if (name === undefined) {\n name = DEFAULT_ENTRY_NAME;\n }\n else {\n if (typeof name !== 'string' || name === '') {\n error('bad-app-name', { name: name + '' });\n }\n }\n if (contains(apps_, name)) {\n error('duplicate-app', { name: name });\n }\n var app = new firebaseApp_FirebaseAppImpl(options, name, namespace);\n apps_[name] = app;\n callAppHooks(app, 'create');\n return app;\n }\n /*\n * Return an array of all the non-deleted FirebaseApps.\n */\n function getApps() {\n // Make a copy so caller cannot mutate the apps list.\n return Object.keys(apps_).map(function (name) { return apps_[name]; });\n }\n /*\n * Register a Firebase Service.\n *\n * firebase.INTERNAL.registerService()\n *\n * TODO: Implement serviceProperties.\n */\n function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) {\n // Cannot re-register a service that already exists\n if (factories[name]) {\n error('duplicate-service', { name: name });\n }\n // Capture the service factory for later service instantiation\n factories[name] = createService;\n // Capture the appHook, if passed\n if (appHook) {\n appHooks[name] = appHook;\n // Run the **new** app hook on all existing apps\n getApps().forEach(function (app) {\n appHook('create', app);\n });\n }\n // The Service namespace is an accessor function ...\n var serviceNamespace = function (appArg) {\n if (appArg === void 0) { appArg = app(); }\n if (typeof appArg[name] !== 'function') {\n // Invalid argument.\n // This happens in the following case: firebase.storage('gs:/')\n error('invalid-app-argument', { name: name });\n }\n // Forward service instance lookup to the FirebaseApp.\n return appArg[name]();\n };\n // ... and a container for service-level properties.\n if (serviceProperties !== undefined) {\n Object(cjs[\"deepExtend\"])(serviceNamespace, serviceProperties);\n }\n // Monkey-patch the serviceNamespace onto the firebase namespace\n namespace[name] = serviceNamespace;\n // Patch the FirebaseAppImpl prototype\n firebaseApp_FirebaseAppImpl.prototype[name] = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var serviceFxn = this._getService.bind(this, name);\n return serviceFxn.apply(this, allowMultipleInstances ? args : []);\n };\n return serviceNamespace;\n }\n /**\n * Patch the top-level firebase namespace with additional properties.\n *\n * firebase.INTERNAL.extendNamespace()\n */\n function extendNamespace(props) {\n Object(cjs[\"deepExtend\"])(namespace, props);\n }\n function callAppHooks(app, eventName) {\n Object.keys(factories).forEach(function (serviceName) {\n // Ignore virtual services\n var factoryName = useAsService(app, serviceName);\n if (factoryName === null) {\n return;\n }\n if (appHooks[factoryName]) {\n appHooks[factoryName](eventName, app);\n }\n });\n }\n // Map the requested service to a registered service name\n // (used to map auth to serverAuth service when needed).\n function useAsService(app, name) {\n if (name === 'serverAuth') {\n return null;\n }\n var useService = name;\n var options = app.options;\n return useService;\n }\n return namespace;\n}\nfunction error(code, args) {\n throw appErrors.create(code, args);\n}\n// TypeScript does not support non-string indexes!\n// let errors: {[code: AppError: string} = {\nvar errors = {\n 'no-app': \"No Firebase App '{$name}' has been created - \" +\n 'call Firebase App.initializeApp()',\n 'bad-app-name': \"Illegal App name: '{$name}\",\n 'duplicate-app': \"Firebase App named '{$name}' already exists\",\n 'app-deleted': \"Firebase App named '{$name}' already deleted\",\n 'duplicate-service': \"Firebase service named '{$name}' already registered\",\n 'sa-not-supported': 'Initializing the Firebase SDK with a service ' +\n 'account is only allowed in a Node.js environment. On client ' +\n 'devices, you should instead initialize the SDK with an api key and ' +\n 'auth domain',\n 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' +\n 'Firebase App instance.'\n};\nvar appErrors = new cjs[\"ErrorFactory\"]('app', 'Firebase', errors);\n\n\n//# sourceMappingURL=firebaseApp.js.map\n\n// CONCATENATED MODULE: ../app/dist/esm/index.js\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"firebase\", function() { return firebase; });\n/**\n * Copyright 2017 Google Inc.\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\nvar firebase = createFirebaseNamespace();\n/* harmony default export */ var esm = __webpack_exports__[\"default\"] = (firebase);\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 8 */,\n/* 9 */,\n/* 10 */,\n/* 11 */\n/***/ (function(module, exports) {\n\nvar g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n/***/ }),\n/* 12 */,\n/* 13 */,\n/* 14 */,\n/* 15 */,\n/* 16 */,\n/* 17 */,\n/* 18 */,\n/* 19 */,\n/* 20 */,\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\nexports.CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n\n//# sourceMappingURL=constants.js.map\n\n\n/***/ }),\n/* 22 */,\n/* 23 */,\n/* 24 */,\n/* 25 */,\n/* 26 */,\n/* 27 */,\n/* 28 */,\n/* 29 */\n/***/ (function(module, exports) {\n\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n/***/ }),\n/* 30 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar constants_1 = __webpack_require__(21);\n/**\n * Throws an error if the provided assertion is falsy\n * @param {*} assertion The assertion to be tested for falsiness\n * @param {!string} message The message to display if the check fails\n */\nexports.assert = function (assertion, message) {\n if (!assertion) {\n throw exports.assertionError(message);\n }\n};\n/**\n * Returns an Error object suitable for throwing.\n * @param {string} message\n * @return {!Error}\n */\nexports.assertionError = function (message) {\n return new Error('Firebase Database (' +\n constants_1.CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message);\n};\n\n//# sourceMappingURL=assert.js.map\n\n\n/***/ }),\n/* 31 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar stringToByteArray = function (str) {\n // TODO(user): Use native implementations if/when available\n var out = [], p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n }\n else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n }\n else if ((c & 0xfc00) == 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param {Array} bytes Array of numbers representing characters.\n * @return {string} Stringification of the array.\n */\nvar byteArrayToString = function (bytes) {\n // TODO(user): Use native implementations if/when available\n var out = [], pos = 0, c = 0;\n while (pos < bytes.length) {\n var c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n }\n else if (c1 > 191 && c1 < 224) {\n var c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n }\n else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n var c2 = bytes[pos++];\n var c3 = bytes[pos++];\n var c4 = bytes[pos++];\n var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n }\n else {\n var c2 = bytes[pos++];\n var c3 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n }\n }\n return out.join('');\n};\n// Static lookup maps, lazily populated by init_()\nexports.base64 = {\n /**\n * Maps bytes to characters.\n * @type {Object}\n * @private\n */\n byteToCharMap_: null,\n /**\n * Maps characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMap_: null,\n /**\n * Maps bytes to websafe characters.\n * @type {Object}\n * @private\n */\n byteToCharMapWebSafe_: null,\n /**\n * Maps websafe characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMapWebSafe_: null,\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n * @type {string}\n */\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n * @type {string}\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n /**\n * Our websafe alphabet.\n * @type {string}\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n * @type {boolean}\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n /**\n * Base64-encode an array of bytes.\n *\n * @param {Array|Uint8Array} input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param {boolean=} opt_webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeByteArray: function (input, opt_webSafe) {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n this.init_();\n var byteToCharMap = opt_webSafe\n ? this.byteToCharMapWebSafe_\n : this.byteToCharMap_;\n var output = [];\n for (var i = 0; i < input.length; i += 3) {\n var byte1 = input[i];\n var haveByte2 = i + 1 < input.length;\n var byte2 = haveByte2 ? input[i + 1] : 0;\n var haveByte3 = i + 2 < input.length;\n var byte3 = haveByte3 ? input[i + 2] : 0;\n var outByte1 = byte1 >> 2;\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n var outByte4 = byte3 & 0x3f;\n if (!haveByte3) {\n outByte4 = 64;\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\n }\n return output.join('');\n },\n /**\n * Base64-encode a string.\n *\n * @param {string} input A string to encode.\n * @param {boolean=} opt_webSafe If true, we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeString: function (input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), opt_webSafe);\n },\n /**\n * Base64-decode a string.\n *\n * @param {string} input to decode.\n * @param {boolean=} opt_webSafe True if we should use the\n * alternative alphabet.\n * @return {string} string representing the decoded value.\n */\n decodeString: function (input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe));\n },\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param {string} input Input to decode.\n * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet.\n * @return {!Array} bytes representing the decoded value.\n */\n decodeStringToByteArray: function (input, opt_webSafe) {\n this.init_();\n var charToByteMap = opt_webSafe\n ? this.charToByteMapWebSafe_\n : this.charToByteMap_;\n var output = [];\n for (var i = 0; i < input.length;) {\n var byte1 = charToByteMap[input.charAt(i++)];\n var haveByte2 = i < input.length;\n var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n var haveByte3 = i < input.length;\n var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n var haveByte4 = i < input.length;\n var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n if (byte3 != 64) {\n var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n if (byte4 != 64) {\n var outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n return output;\n },\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_: function () {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n // We want quick mappings back and forth, so we precompute two maps.\n for (var i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n/**\n * URL-safe base64 encoding\n * @param {!string} str\n * @return {!string}\n */\nexports.base64Encode = function (str) {\n var utf8Bytes = stringToByteArray(str);\n return exports.base64.encodeByteArray(utf8Bytes, true);\n};\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param {string} str To be decoded\n * @return {?string} Decoded result, if possible\n */\nexports.base64Decode = function (str) {\n try {\n return exports.base64.decodeString(str, true);\n }\n catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n\n//# sourceMappingURL=crypt.js.map\n\n\n/***/ }),\n/* 32 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nfunction jsonEval(str) {\n return JSON.parse(str);\n}\nexports.jsonEval = jsonEval;\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nfunction stringify(data) {\n return JSON.stringify(data);\n}\nexports.stringify = stringify;\n\n//# sourceMappingURL=json.js.map\n\n\n/***/ }),\n/* 33 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/\nexports.contains = function (obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\nexports.safeGet = function (obj, key) {\n if (Object.prototype.hasOwnProperty.call(obj, key))\n return obj[key];\n // else return undefined.\n};\n/**\n * Enumerates the keys/values in an object, excluding keys defined on the prototype.\n *\n * @param {?Object.} obj Object to enumerate.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexports.forEach = function (obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n};\n/**\n * Copies all the (own) properties from one object to another.\n * @param {!Object} objTo\n * @param {!Object} objFrom\n * @return {!Object} objTo\n */\nexports.extend = function (objTo, objFrom) {\n exports.forEach(objFrom, function (key, value) {\n objTo[key] = value;\n });\n return objTo;\n};\n/**\n * Returns a clone of the specified object.\n * @param {!Object} obj\n * @return {!Object} cloned obj.\n */\nexports.clone = function (obj) {\n return exports.extend({}, obj);\n};\n/**\n * Returns true if obj has typeof \"object\" and is not null. Unlike goog.isObject(), does not return true\n * for functions.\n *\n * @param obj {*} A potential object.\n * @returns {boolean} True if it's an object.\n */\nexports.isNonNullObject = function (obj) {\n return typeof obj === 'object' && obj !== null;\n};\nexports.isEmpty = function (obj) {\n for (var key in obj) {\n return false;\n }\n return true;\n};\nexports.getCount = function (obj) {\n var rv = 0;\n for (var key in obj) {\n rv++;\n }\n return rv;\n};\nexports.map = function (obj, f, opt_obj) {\n var res = {};\n for (var key in obj) {\n res[key] = f.call(opt_obj, obj[key], key, obj);\n }\n return res;\n};\nexports.findKey = function (obj, fn, opt_this) {\n for (var key in obj) {\n if (fn.call(opt_this, obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n};\nexports.findValue = function (obj, fn, opt_this) {\n var key = exports.findKey(obj, fn, opt_this);\n return key && obj[key];\n};\nexports.getAnyKey = function (obj) {\n for (var key in obj) {\n return key;\n }\n};\nexports.getValues = function (obj) {\n var res = [];\n var i = 0;\n for (var key in obj) {\n res[i++] = obj[key];\n }\n return res;\n};\n/**\n * Tests whether every key/value pair in an object pass the test implemented\n * by the provided function\n *\n * @param {?Object.} obj Object to test.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexports.every = function (obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n if (!fn(key, obj[key])) {\n return false;\n }\n }\n }\n return true;\n};\n\n//# sourceMappingURL=obj.js.map\n\n\n/***/ }),\n/* 34 */,\n/* 35 */,\n/* 36 */,\n/* 37 */,\n/* 38 */,\n/* 39 */,\n/* 40 */,\n/* 41 */,\n/* 42 */,\n/* 43 */,\n/* 44 */,\n/* 45 */,\n/* 46 */,\n/* 47 */,\n/* 48 */,\n/* 49 */,\n/* 50 */,\n/* 51 */,\n/* 52 */,\n/* 53 */,\n/* 54 */,\n/* 55 */,\n/* 56 */,\n/* 57 */,\n/* 58 */,\n/* 59 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(60);\nmodule.exports = __webpack_require__(7).default;\n\n\n/***/ }),\n/* 60 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__ = __webpack_require__(61);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_polyfills_promise__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_shims_Array__ = __webpack_require__(65);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_shims_Array___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__src_shims_Array__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_shims_String__ = __webpack_require__(66);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_shims_String___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__src_shims_String__);\n/**\n * Copyright 2017 Google Inc.\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\n\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 61 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {/**\n * Copyright 2017 Google Inc.\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 */\nvar __global = (function () {\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n throw new Error('unable to locate global object');\n})();\n// Polyfill Promise\nif (typeof Promise === 'undefined') {\n // HACK: TS throws an error if I attempt to use 'dot-notation'\n __global['Promise'] = Promise = __webpack_require__(62);\n}\n\n//# sourceMappingURL=promise.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11)))\n\n/***/ }),\n/* 62 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(setImmediate) {\n\n// Store setTimeout reference so promise-polyfill will be unaffected by\n// other code modifying setTimeout (like sinon.useFakeTimers())\nvar setTimeoutFunc = setTimeout;\n\nfunction noop() {}\n\n// Polyfill for Function.prototype.bind\nfunction bind(fn, thisArg) {\n return function() {\n fn.apply(thisArg, arguments);\n };\n}\n\nfunction Promise(fn) {\n if (!(this instanceof Promise))\n throw new TypeError('Promises must be constructed via new');\n if (typeof fn !== 'function') throw new TypeError('not a function');\n this._state = 0;\n this._handled = false;\n this._value = undefined;\n this._deferreds = [];\n\n doResolve(fn, this);\n}\n\nfunction handle(self, deferred) {\n while (self._state === 3) {\n self = self._value;\n }\n if (self._state === 0) {\n self._deferreds.push(deferred);\n return;\n }\n self._handled = true;\n Promise._immediateFn(function() {\n var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;\n if (cb === null) {\n (self._state === 1 ? resolve : reject)(deferred.promise, self._value);\n return;\n }\n var ret;\n try {\n ret = cb(self._value);\n } catch (e) {\n reject(deferred.promise, e);\n return;\n }\n resolve(deferred.promise, ret);\n });\n}\n\nfunction resolve(self, newValue) {\n try {\n // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n if (newValue === self)\n throw new TypeError('A promise cannot be resolved with itself.');\n if (\n newValue &&\n (typeof newValue === 'object' || typeof newValue === 'function')\n ) {\n var then = newValue.then;\n if (newValue instanceof Promise) {\n self._state = 3;\n self._value = newValue;\n finale(self);\n return;\n } else if (typeof then === 'function') {\n doResolve(bind(then, newValue), self);\n return;\n }\n }\n self._state = 1;\n self._value = newValue;\n finale(self);\n } catch (e) {\n reject(self, e);\n }\n}\n\nfunction reject(self, newValue) {\n self._state = 2;\n self._value = newValue;\n finale(self);\n}\n\nfunction finale(self) {\n if (self._state === 2 && self._deferreds.length === 0) {\n Promise._immediateFn(function() {\n if (!self._handled) {\n Promise._unhandledRejectionFn(self._value);\n }\n });\n }\n\n for (var i = 0, len = self._deferreds.length; i < len; i++) {\n handle(self, self._deferreds[i]);\n }\n self._deferreds = null;\n}\n\nfunction Handler(onFulfilled, onRejected, promise) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.promise = promise;\n}\n\n/**\n * Take a potentially misbehaving resolver function and make sure\n * onFulfilled and onRejected are only called once.\n *\n * Makes no guarantees about asynchrony.\n */\nfunction doResolve(fn, self) {\n var done = false;\n try {\n fn(\n function(value) {\n if (done) return;\n done = true;\n resolve(self, value);\n },\n function(reason) {\n if (done) return;\n done = true;\n reject(self, reason);\n }\n );\n } catch (ex) {\n if (done) return;\n done = true;\n reject(self, ex);\n }\n}\n\nPromise.prototype['catch'] = function(onRejected) {\n return this.then(null, onRejected);\n};\n\nPromise.prototype.then = function(onFulfilled, onRejected) {\n var prom = new this.constructor(noop);\n\n handle(this, new Handler(onFulfilled, onRejected, prom));\n return prom;\n};\n\nPromise.prototype['finally'] = function(callback) {\n var constructor = this.constructor;\n return this.then(\n function(value) {\n return constructor.resolve(callback()).then(function() {\n return value;\n });\n },\n function(reason) {\n return constructor.resolve(callback()).then(function() {\n return constructor.reject(reason);\n });\n }\n );\n};\n\nPromise.all = function(arr) {\n return new Promise(function(resolve, reject) {\n if (!arr || typeof arr.length === 'undefined')\n throw new TypeError('Promise.all accepts an array');\n var args = Array.prototype.slice.call(arr);\n if (args.length === 0) return resolve([]);\n var remaining = args.length;\n\n function res(i, val) {\n try {\n if (val && (typeof val === 'object' || typeof val === 'function')) {\n var then = val.then;\n if (typeof then === 'function') {\n then.call(\n val,\n function(val) {\n res(i, val);\n },\n reject\n );\n return;\n }\n }\n args[i] = val;\n if (--remaining === 0) {\n resolve(args);\n }\n } catch (ex) {\n reject(ex);\n }\n }\n\n for (var i = 0; i < args.length; i++) {\n res(i, args[i]);\n }\n });\n};\n\nPromise.resolve = function(value) {\n if (value && typeof value === 'object' && value.constructor === Promise) {\n return value;\n }\n\n return new Promise(function(resolve) {\n resolve(value);\n });\n};\n\nPromise.reject = function(value) {\n return new Promise(function(resolve, reject) {\n reject(value);\n });\n};\n\nPromise.race = function(values) {\n return new Promise(function(resolve, reject) {\n for (var i = 0, len = values.length; i < len; i++) {\n values[i].then(resolve, reject);\n }\n });\n};\n\n// Use polyfill for setImmediate for performance gains\nPromise._immediateFn =\n (typeof setImmediate === 'function' &&\n function(fn) {\n setImmediate(fn);\n }) ||\n function(fn) {\n setTimeoutFunc(fn, 0);\n };\n\nPromise._unhandledRejectionFn = function _unhandledRejectionFn(err) {\n if (typeof console !== 'undefined' && console) {\n console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console\n }\n};\n\nmodule.exports = Promise;\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(63).setImmediate))\n\n/***/ }),\n/* 63 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global) {var apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\n__webpack_require__(64);\n// On some exotic environments, it's not clear which object `setimmeidate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11)))\n\n/***/ }),\n/* 64 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a ';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(27);\nvar Constants_1 = __webpack_require__(15);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(14);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(29)))\n\n/***/ }),\n/* 57 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 58 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(26);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(6);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */,\n/* 79 */,\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = __webpack_require__(81);\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(7);\nvar Database_1 = __webpack_require__(34);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(38);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(23);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(28);\nvar INTERNAL = __webpack_require__(113);\nvar TEST_ACCESS = __webpack_require__(114);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(24);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(37);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(24);\nvar Event_1 = __webpack_require__(87);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(89);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(25);\nvar ListenComplete_1 = __webpack_require__(90);\nvar Merge_1 = __webpack_require__(91);\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(48);\nvar Path_1 = __webpack_require__(3);\nvar SyncPoint_1 = __webpack_require__(49);\nvar WriteTree_1 = __webpack_require__(97);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(3);\nvar Operation_1 = __webpack_require__(9);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar Overwrite_1 = __webpack_require__(48);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(26);\nvar ViewProcessor_1 = __webpack_require__(93);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar CacheNode_1 = __webpack_require__(20);\nvar ViewCache_1 = __webpack_require__(50);\nvar EventGenerator_1 = __webpack_require__(96);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(9);\nvar Change_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(4);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(94);\nvar Change_1 = __webpack_require__(10);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar KeyIndex_1 = __webpack_require__(12);\nvar ImmutableTree_1 = __webpack_require__(25);\nvar Path_1 = __webpack_require__(3);\nvar CompleteChildSource_1 = __webpack_require__(95);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(20);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(6);\nvar Change_1 = __webpack_require__(10);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar CompoundWrite_1 = __webpack_require__(98);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(25);\nvar Path_1 = __webpack_require__(3);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(6);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(5);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(51);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar EventEmitter_1 = __webpack_require__(53);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(53);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(55);\nvar WebSocketConnection_1 = __webpack_require__(56);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(57);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(12);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar ValueIndex_1 = __webpack_require__(40);\nvar PathIndex_1 = __webpack_require__(44);\nvar IndexedFilter_1 = __webpack_require__(26);\nvar LimitedFilter_1 = __webpack_require__(110);\nvar RangedFilter_1 = __webpack_require__(58);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(58);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Node_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(10);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(23);\nvar DataSnapshot_1 = __webpack_require__(24);\nvar Path_1 = __webpack_require__(3);\nvar Tree_1 = __webpack_require__(112);\nvar PriorityIndex_1 = __webpack_require__(4);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(45);\nvar validation_1 = __webpack_require__(8);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(13);\nvar ChildrenNode_1 = __webpack_require__(5);\nvar Repo_1 = __webpack_require__(19);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 113 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(56);\nvar BrowserPollConnection_1 = __webpack_require__(55);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 114 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(36);\nvar PersistentConnection_1 = __webpack_require__(52);\nvar RepoManager_1 = __webpack_require__(28);\nvar Connection_1 = __webpack_require__(54);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[80]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\nvar logger_1 = require(\"@firebase/logger\");\nvar logClient = new logger_1.Logger('@firebase/database');\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n logClient.logLevel = logger_1.LogLevel.VERBOSE;\n exports.logger = logClient.log.bind(logClient);\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = \"FIREBASE FATAL ERROR: \" + buildLogMessage_.apply(void 0, var_args);\n logClient.error(message);\n throw new Error(message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n logClient.warn(message);\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n tslib_1.__extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 6\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n (!exports.isValidKey(parsedUrl.repoInfo.namespace) &&\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n tslib_1.__extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 12\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 19\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 20\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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 */\nimport { instances } from './src/logger';\nexport function setLogLevel(level) {\n instances.forEach(function (inst) {\n inst.logLevel = level;\n });\n}\nexport { Logger, LogLevel } from './src/logger';\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 container for all of the Logger instances\n */\nexport var instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\n/**\n * The default log level\n */\nvar defaultLogLevel = LogLevel.INFO;\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nvar defaultLogHandler = function (instance, logType) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (logType < instance.logLevel)\n return;\n var now = new Date().toISOString();\n switch (logType) {\n /**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\n case LogLevel.DEBUG:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.VERBOSE:\n console.log.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.INFO:\n console.info.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.WARN:\n console.warn.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n case LogLevel.ERROR:\n console.error.apply(console, [\"[\" + now + \"] \" + instance.name + \":\"].concat(args));\n break;\n default:\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\n }\n};\nvar Logger = /** @class */ (function () {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n function Logger(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The log handler for the Logger instance.\n */\n this._logHandler = defaultLogHandler;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n Object.defineProperty(Logger.prototype, \"logLevel\", {\n get: function () {\n return this._logLevel;\n },\n set: function (val) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Logger.prototype, \"logHandler\", {\n get: function () {\n return this._logHandler;\n },\n set: function (val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * The functions below are all based on the `console` interface\n */\n Logger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));\n };\n Logger.prototype.log = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));\n };\n Logger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));\n };\n Logger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));\n };\n Logger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));\n };\n return Logger;\n}());\nexport { Logger };\n\n//# sourceMappingURL=logger.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../logger/dist/esm/src/logger.js\n// module id = null\n// module chunks = ","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n tslib_1.__extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 27\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.initializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 28\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n Database.prototype.ref = function (path) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference_1.Reference) {\n return this.refFromURL(path.toString());\n }\n return path !== undefined ? this.root_.child(path) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2 /*return*/];\n });\n });\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString) {\n var results = {};\n if (queryString.startsWith('?')) {\n queryString = queryString.substring(1);\n }\n for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) {\n var segment = _a[_i];\n if (segment.length === 0) {\n continue;\n }\n var kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n }\n else {\n util_1.warn(\"Invalid query segment '\" + segment + \"' in query '\" + queryString + \"'\");\n }\n }\n return results;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if ((!namespace || namespace == 'undefined') &&\n parsedUrl.domain !== 'localhost') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host, path, and query string.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n var questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n else {\n colonInd = dataURL.length;\n }\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Support `ns` query param if subdomain not already set\n if (subdomain === '' && 'ns' in queryParams) {\n subdomain = queryParams['ns'];\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost || this.isCustomHost();\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n tslib_1.__extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n tslib_1.__extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body) {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 56\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 57\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 58\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n tslib_1.__extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar tslib_1 = require(\"tslib\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 112\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 113\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 114\n// module chunks = 0","/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([3],{\n\n/***/ 120:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(121);\n\n\n/***/ }),\n\n/***/ 121:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: /tmp/tmp-208812ou3wR5n5ZCvd/node_modules/tslib/tslib.es6.js\nvar tslib_es6 = __webpack_require__(2);\n\n// EXTERNAL MODULE: ../util/dist/cjs/index.js\nvar cjs = __webpack_require__(0);\nvar cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/errors.js\n/**\n * Copyright 2017 Google Inc.\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\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED: 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\n};\nvar ERROR_MAP = (errors__a = {},\n errors__a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n errors__a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n errors__a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n errors__a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n errors__a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n errors__a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n errors__a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n errors__a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n errors__a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n errors__a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n errors__a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n errors__a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n errors__a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n errors__a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n errors__a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n errors__a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n errors__a[CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}',\n errors__a[CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}',\n errors__a[CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.',\n errors__a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n errors__a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n errors__a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n errors__a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n errors__a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n errors__a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n errors__a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n errors__a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n errors__a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n errors__a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n errors__a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n errors__a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n errors__a[CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.',\n errors__a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n errors__a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n errors__a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n errors__a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n errors__a[CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.',\n errors__a[CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.',\n errors__a);\n/* harmony default export */ var errors = ({\n codes: CODES,\n map: ERROR_MAP\n});\nvar errors__a;\n\n//# sourceMappingURL=errors.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/db-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\nvar db_interface_DBInterface = /** @class */ (function () {\n /**\n * @param {string} dbName\n * @param {number} dbVersion\n */\n function DBInterface(dbName, dbVersion) {\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n this.DB_NAME_ = dbName;\n this.dbVersion_ = dbVersion;\n this.openDbPromise_ = null;\n this.TRANSACTION_READ_WRITE = 'readwrite';\n }\n /**\n * Get the indexedDB as a promsie.\n * @protected\n * @return {!Promise} The IndexedDB database\n */\n DBInterface.prototype.openDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(_this.DB_NAME_, _this.dbVersion_);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n try {\n var db = event.target.result;\n _this.onDBUpgrade(db, event);\n }\n catch (err) {\n // close the database as it can't be used.\n db.close();\n reject(err);\n }\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {!Promise} Returns the result of the promise chain.\n */\n DBInterface.prototype.closeDatabase = function () {\n var _this = this;\n return Promise.resolve().then(function () {\n if (_this.openDbPromise_) {\n return _this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n });\n };\n /**\n * @protected\n * @param {!IDBDatabase} db\n */\n DBInterface.prototype.onDBUpgrade = function (db, event) {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n return DBInterface;\n}());\n/* harmony default export */ var db_interface = (db_interface_DBInterface);\n\n//# sourceMappingURL=db-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n/* harmony default export */ var array_buffer_to_base64 = (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n});\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/fcm-details.js\n/**\n * Copyright 2017 Google Inc.\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\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n]);\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: DEFAULT_PUBLIC_VAPID_KEY\n};\n/* harmony default export */ var fcm_details = ({\n DEFAULT_PUBLIC_VAPID_KEY: DEFAULT_PUBLIC_VAPID_KEY,\n SUBSCRIPTION_DETAILS: SUBSCRIPTION_DETAILS,\n ENDPOINT: 'https://fcm.googleapis.com'\n // ENDPOINT: 'https://jmt17.google.com'\n});\n\n//# sourceMappingURL=fcm-details.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/iid-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nvar iid_model_IIDModel = /** @class */ (function () {\n function IIDModel() {\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n }\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {Uint8Array} publicVapidKey The public VAPID key.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n IIDModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== fcm_details.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = array_buffer_to_base64(publicVapidKey);\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .catch(function () {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED);\n })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Update the underlying token details for fcmToken.\n */\n IIDModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"authorized_entity=\" + senderId + \"&\") +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== fcm_details.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = array_buffer_to_base64(publicVapidKey);\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var updateOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUpdateBody\n };\n var updateFetchRes;\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', updateOptions)\n .then(function (fetchResponse) {\n updateFetchRes = fetchResponse;\n return fetchResponse.json();\n })\n .catch(function () {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_FAILED);\n })\n .then(function (fcmTokenResponse) {\n if (!updateFetchRes.ok) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UPDATE_NO_TOKEN);\n }\n return fcmTokenResponse['token'];\n });\n };\n /**\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\n */\n IIDModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\n var _this = this;\n var fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"pushSet=\" + fcmPushSet);\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var unsubscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUnsubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions).then(function (fetchResponse) {\n if (!fetchResponse.ok) {\n return fetchResponse.json().then(function (fcmTokenResponse) {\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(errors.codes.TOKEN_UNSUBSCRIBE_FAILED, {\n message: message\n });\n }\n }, function (err) {\n throw _this.errorFactory_.create(errors.codes.TOKEN_UNSUBSCRIBE_FAILED);\n });\n }\n });\n };\n return IIDModel;\n}());\n/* harmony default export */ var iid_model = (iid_model_IIDModel);\n\n//# sourceMappingURL=iid-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/clean-v1-undefined.js\n/**\n * Copyright 2017 Google Inc.\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 * There seems to have been a bug in the messaging SDK versions <= 4.9.x\n * where the IndexedDB model was using a database name of 'undefined'.\n *\n * In 4.10.x we changed the model implementation, but kept the database\n * name as it should have been. This however introduced an issue where\n * two tokens were pointing to the same underlying PushSubscription.\n *\n * This code will look for the undefined database and delete any of the\n * underlying tokens.\n */\n\nvar OLD_DB_NAME = 'undefined';\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\nfunction handleDb(db) {\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // We found a database with the name 'undefined', but our expected object\n // store isn't defined.\n return;\n }\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\n var iidModel = new iid_model();\n var openCursorRequest = objectStore.openCursor();\n openCursorRequest.onerror = function (event) {\n // NOOP - Nothing we can do.\n console.warn('Unable to cleanup old IDB.', event);\n };\n openCursorRequest.onsuccess = function () {\n var cursor = openCursorRequest.result;\n if (cursor) {\n // cursor.value contains the current record being iterated through\n // this is where you'd do something with the result\n var tokenDetails = cursor.value;\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\n cursor.continue();\n }\n else {\n db.close();\n indexedDB.deleteDatabase(OLD_DB_NAME);\n }\n };\n}\nfunction cleanV1() {\n var request = indexedDB.open(OLD_DB_NAME);\n request.onerror = function (event) {\n // NOOP - Nothing we can do.\n };\n request.onsuccess = function (event) {\n var db = request.result;\n handleDb(db);\n };\n}\n\n\n//# sourceMappingURL=clean-v1-undefined.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/token-details-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar DB_NAME = 'fcm_token_details_db';\nvar DB_VERSION = 2;\n/** @record */\nfunction ValidateInput() { }\n/** @type {string|undefined} */\nValidateInput.prototype.fcmToken;\n/** @type {string|undefined} */\nValidateInput.prototype.swScope;\n/** @type {string|undefined} */\nValidateInput.prototype.vapidKey;\n/** @type {PushSubscription|undefined} */\nValidateInput.prototype.subscription;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmSenderId;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmPushSet;\nvar token_details_model_TokenDetailsModel = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](TokenDetailsModel, _super);\n function TokenDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n TokenDetailsModel.prototype.onDBUpgrade = function (db, evt) {\n if (evt.oldVersion < 1) {\n // New IDB instance\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n }\n if (evt.oldVersion < 2) {\n // Prior to version 2, we were using either 'fcm_token_details_db'\n // or 'undefined' as the database name due to bug in the SDK\n // So remove the old tokens and databases.\n cleanV1();\n }\n };\n /**\n * This method takes an object and will check for known arguments and\n * validate the input.\n * @private\n * @param {!ValidateInput} input\n * @return {!Promise} Returns promise that resolves if input is valid,\n * rejects otherwise.\n */\n TokenDetailsModel.prototype.validateInputs_ = function (input) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (input.fcmToken) {\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN))];\n }\n }\n if (input.swScope) {\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE))];\n }\n }\n if (input.vapidKey) {\n if (!(input.vapidKey instanceof Uint8Array) ||\n input.vapidKey.length !== 65) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY))];\n }\n }\n if (input.subscription) {\n if (!(input.subscription instanceof PushSubscription)) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SUBSCRIPTION))];\n }\n }\n if (input.fcmSenderId) {\n if (typeof input.fcmSenderId !== 'string' ||\n input.fcmSenderId.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID))];\n }\n }\n if (input.fcmPushSet) {\n if (typeof input.fcmPushSet !== 'string' ||\n input.fcmPushSet.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.BAD_PUSH_SET))];\n }\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\n var _this = this;\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN));\n }\n return this.validateInputs_({ fcmToken: fcmToken })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Given a service worker scope, this method will look up the details in\n * indexedDB.\n * @public\n * @param {string} swScope\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\n var _this = this;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n return this.validateInputs_({ swScope: swScope })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @param {{swScope: !string, vapidKey: !string,\n * subscription: !PushSubscription, fcmSenderId: !string, fcmToken: !string,\n * fcmPushSet: !string}} input A plain js object containing args to save.\n * @return {Promise}\n */\n TokenDetailsModel.prototype.saveTokenDetails = function (_a) {\n var _this = this;\n var swScope = _a.swScope, vapidKey = _a.vapidKey, subscription = _a.subscription, fcmSenderId = _a.fcmSenderId, fcmToken = _a.fcmToken, fcmPushSet = _a.fcmPushSet;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n if (!vapidKey) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY));\n }\n if (!subscription) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SUBSCRIPTION));\n }\n if (!fcmSenderId) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SENDER_ID));\n }\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_TOKEN));\n }\n if (!fcmPushSet) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_PUSH_SET));\n }\n return this.validateInputs_({\n swScope: swScope,\n vapidKey: vapidKey,\n subscription: subscription,\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet\n })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n /**\n * @dict\n */\n var details = {\n swScope: swScope,\n vapidKey: array_buffer_to_base64(vapidKey),\n endpoint: subscription.endpoint,\n auth: array_buffer_to_base64(subscription['getKey']('auth')),\n p256dh: array_buffer_to_base64(subscription['getKey']('p256dh')),\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n createTime: Date.now()\n };\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenDetailsModel.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenDetailsModel;\n}(db_interface));\n/* harmony default export */ var token_details_model = (token_details_model_TokenDetailsModel);\n\n//# sourceMappingURL=token-details-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/vapid-details-model.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\nvar FCM_VAPID_OBJ_STORE = 'fcm_vapid_object_Store';\nvar vapid_details_model_DB_NAME = 'fcm_vapid_details_db';\nvar vapid_details_model_DB_VERSION = 1;\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\nvar vapid_details_model_VapidDetailsModel = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](VapidDetailsModel, _super);\n function VapidDetailsModel() {\n return _super.call(this, vapid_details_model_DB_NAME, vapid_details_model_DB_VERSION) || this;\n }\n /**\n * @override\n * @param {IDBDatabase} db\n */\n VapidDetailsModel.prototype.onDBUpgrade = function (db) {\n db.createObjectStore(FCM_VAPID_OBJ_STORE, {\n keyPath: 'swScope'\n });\n };\n /**\n * Given a service worker scope, this method will look up the vapid key\n * in indexedDB.\n */\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function () {\n reject(scopeRequest.error);\n };\n scopeRequest.onsuccess = function () {\n var result = scopeRequest.result;\n var vapidKey = null;\n if (result) {\n vapidKey = result.vapidKey;\n }\n resolve(vapidKey);\n };\n });\n });\n };\n /**\n * Save a vapid key against a swScope for later date.\n */\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\n var _this = this;\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_SCOPE));\n }\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n return Promise.reject(this.errorFactory_.create(errors.codes.BAD_VAPID_KEY));\n }\n var details = {\n swScope: swScope,\n vapidKey: vapidKey\n };\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM VAPID key for a SW scope.\n * Resolves once the scope/vapid details have been deleted and returns the\n * deleted vapid key.\n */\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\n var _this = this;\n return this.getVapidFromSWScope(swScope).then(function (vapidKey) {\n if (!vapidKey) {\n throw _this.errorFactory_.create(errors.codes.DELETE_SCOPE_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.delete(swScope);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n if (request.result === 0) {\n reject(_this.errorFactory_.create(errors.codes.FAILED_DELETE_VAPID_KEY));\n return;\n }\n resolve(vapidKey);\n };\n });\n });\n });\n };\n return VapidDetailsModel;\n}(db_interface));\n/* harmony default export */ var vapid_details_model = (vapid_details_model_VapidDetailsModel);\n\n//# sourceMappingURL=vapid-details-model.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/notification-permission.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var notification_permission = ({\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n});\n\n//# sourceMappingURL=notification-permission.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/controller-interface.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nvar TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\nvar controller_interface_ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new cjs[\"ErrorFactory\"]('messaging', 'Messaging', errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenDetailsModel_ = new token_details_model();\n this.vapidDetailsModel_ = new vapid_details_model();\n this.iidModel_ = new iid_model();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete(); };\n }\n /**\n * @export\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== notification_permission.granted) {\n if (currentPermission === notification_permission.denied) {\n return Promise.reject(this.errorFactory_.create(errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n var swReg;\n return this.getSWRegistration_()\n .then(function (reg) {\n swReg = reg;\n return _this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(function (tokenDetails) {\n if (tokenDetails) {\n return _this.manageExistingToken(tokenDetails, swReg);\n }\n return _this.getNewToken(swReg);\n });\n };\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n ControllerInterface.prototype.manageExistingToken = function (tokenDetails, swReg) {\n var _this = this;\n return this.isTokenStillValid(tokenDetails).then(function (isValid) {\n if (isValid) {\n var now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n }\n else {\n return _this.updateToken(tokenDetails, swReg);\n }\n }\n else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n return _this.getNewToken(swReg);\n });\n }\n });\n };\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n ControllerInterface.prototype.isTokenStillValid = function (tokenDetails) {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(function (publicKey) {\n if (array_buffer_to_base64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n };\n ControllerInterface.prototype.updateToken = function (tokenDetails, swReg) {\n var _this = this;\n var publicVapidKey;\n var updatedToken;\n var subscription;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.updateToken(_this.messagingSenderId_, tokenDetails['fcmToken'], tokenDetails['fcmPushSet'], subscription, publicVapidKey);\n })\n .catch(function (err) {\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n })\n .then(function (token) {\n updatedToken = token;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return updatedToken;\n });\n };\n ControllerInterface.prototype.getNewToken = function (swReg) {\n var _this = this;\n var publicVapidKey;\n var subscription;\n var tokenDetails;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.getToken(_this.messagingSenderId_, subscription, publicVapidKey);\n })\n .then(function (iidTokenDetails) {\n tokenDetails = iidTokenDetails;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return tokenDetails['token'];\n });\n };\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(function (details) {\n return _this.iidModel_.deleteToken(details['fcmSenderId'], details['fcmToken'], details['fcmPushSet']);\n })\n .then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n ControllerInterface.prototype.getPublicVapidKey_ = function () {\n throw this.errorFactory_.create(errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!string} b64PublicKey\n */\n ControllerInterface.prototype.usePublicVapidKey = function (b64PublicKey) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n ControllerInterface.prototype.getTokenDetailsModel = function () {\n return this.tokenDetailsModel_;\n };\n ControllerInterface.prototype.getVapidDetailsModel = function () {\n return this.vapidDetailsModel_;\n };\n /**\n * @protected\n * @returns {IIDModel}\n */\n ControllerInterface.prototype.getIIDModel = function () {\n return this.iidModel_;\n };\n return ControllerInterface;\n}());\n/* harmony default export */ var controller_interface = (controller_interface_ControllerInterface);\n\n//# sourceMappingURL=controller-interface.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/worker-page-message.js\n/**\n * Copyright 2017 Google Inc.\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// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\n/* harmony default export */ var worker_page_message = ({\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n});\n\n//# sourceMappingURL=worker-page-message.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/models/default-sw.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var default_sw = ({\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n});\n\n//# sourceMappingURL=default-sw.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/helpers/base64-to-array-buffer.js\n/**\n * Copyright 2017 Google Inc.\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/* harmony default export */ var base64_to_array_buffer = (function (base64String) {\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\n var base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n var rawData = window.atob(base64);\n var outputArray = new Uint8Array(rawData.length);\n for (var i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n});\n\n//# sourceMappingURL=base64-to-array-buffer.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/window-controller.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n\n\nvar window_controller_WindowController = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n _this.messageObserver_ = null;\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(cjs[\"createSubscribe\"])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n var _this = this;\n return tslib_es6[\"__generator\"](this, function (_a) {\n if (Notification.permission === notification_permission.granted) {\n return [2 /*return*/];\n }\n return [2 /*return*/, new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === notification_permission.granted) {\n return resolve();\n }\n else if (result === notification_permission.denied) {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(managePermissionResult);\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n })];\n });\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\n }\n var parsedKey = base64_to_array_buffer(publicKey);\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(errors.codes.PUBLIC_KEY_DECRYPTION_FAILED);\n }\n this.publicVapidKeyToUse_ = parsedKey;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(default_sw.path, {\n scope: default_sw.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n WindowController.prototype.getPublicVapidKey_ = function () {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n return Promise.resolve(fcm_details.DEFAULT_PUBLIC_VAPID_KEY);\n };\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise}\n */\n WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n case worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[worker_page_message.PARAMS.DATA];\n if (_this.messageObserver_) {\n _this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(controller_interface));\n/* harmony default export */ var window_controller = (window_controller_WindowController);\n\n//# sourceMappingURL=window-controller.js.map\n\n// CONCATENATED MODULE: ../messaging/dist/esm/src/controllers/sw-controller.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\nvar FCM_MSG = 'FCM_MSG';\nvar sw_controller_SWController = /** @class */ (function (_super) {\n tslib_es6[\"__extends\"](SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle_1 = notificationDetails.title || '';\n return _this.getSWRegistration_().then(function (reg) {\n return reg.showNotification(notificationTitle_1, notificationDetails);\n });\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getSWRegistration_()\n .then(function (registration) {\n return registration.pushManager\n .getSubscription()\n .then(function (subscription) {\n // TODO: Check if it's still valid\n // TODO: If not, then update token\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n var tokenDetailsModel = _this.getTokenDetailsModel();\n return tokenDetailsModel\n .getTokenDetailsFromSWScope(registration.scope)\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n // This should rarely occure, but could if indexedDB\n // is corrupted or wiped\n throw err;\n }\n // Attempt to delete the token if we know it's bad\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n });\n });\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n if (!msgPayload['notification']) {\n // Nothing to do.\n return;\n }\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient.focus();\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (!callback || typeof callback !== 'function') {\n throw this.errorFactory_.create(errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url, self.location).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url, self.location).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n return suitableClient;\n }\n return null;\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n return tslib_es6[\"__awaiter\"](this, void 0, void 0, function () {\n return tslib_es6[\"__generator\"](this, function (_a) {\n // NOTE: This returns a promise in case this API is abstracted later on to\n // do additional work\n if (!client) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(errors.codes.NO_WINDOW_CLIENT_TO_MSG))];\n }\n client.postMessage(message);\n return [2 /*return*/];\n });\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n /**\n * This will return the default VAPID key or the uint8array version of the\n * public VAPID key provided by the developer.\n */\n SWController.prototype.getPublicVapidKey_ = function () {\n var _this = this;\n return this.getSWRegistration_()\n .then(function (swReg) {\n return _this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope);\n })\n .then(function (vapidKeyFromDatabase) {\n if (vapidKeyFromDatabase === null) {\n return fcm_details.DEFAULT_PUBLIC_VAPID_KEY;\n }\n return vapidKeyFromDatabase;\n });\n };\n return SWController;\n}(controller_interface));\n/* harmony default export */ var sw_controller = (sw_controller_SWController);\n\n//# sourceMappingURL=sw-controller.js.map\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// CONCATENATED MODULE: ../messaging/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerMessaging\"] = registerMessaging;\n/**\n * Copyright 2017 Google Inc.\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\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new sw_controller(app);\n }\n // Assume we are in the window context.\n return new window_controller(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: window_controller\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(esm[\"firebase\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[120]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/messaging');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./messaging/index.js\n// module id = 120\n// module chunks = 3","/**\n * Copyright 2017 Google Inc.\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 toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\nexport default (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n});\n\n//# sourceMappingURL=array-buffer-to-base64.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/array-buffer-to-base64.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * There seems to have been a bug in the messaging SDK versions <= 4.9.x\n * where the IndexedDB model was using a database name of 'undefined'.\n *\n * In 4.10.x we changed the model implementation, but kept the database\n * name as it should have been. This however introduced an issue where\n * two tokens were pointing to the same underlying PushSubscription.\n *\n * This code will look for the undefined database and delete any of the\n * underlying tokens.\n */\nimport IIDModel from '../models/iid-model';\nvar OLD_DB_NAME = 'undefined';\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\nfunction handleDb(db) {\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // We found a database with the name 'undefined', but our expected object\n // store isn't defined.\n return;\n }\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\n var iidModel = new IIDModel();\n var openCursorRequest = objectStore.openCursor();\n openCursorRequest.onerror = function (event) {\n // NOOP - Nothing we can do.\n console.warn('Unable to cleanup old IDB.', event);\n };\n openCursorRequest.onsuccess = function () {\n var cursor = openCursorRequest.result;\n if (cursor) {\n // cursor.value contains the current record being iterated through\n // this is where you'd do something with the result\n var tokenDetails = cursor.value;\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\n cursor.continue();\n }\n else {\n db.close();\n indexedDB.deleteDatabase(OLD_DB_NAME);\n }\n };\n}\nfunction cleanV1() {\n var request = indexedDB.open(OLD_DB_NAME);\n request.onerror = function (event) {\n // NOOP - Nothing we can do.\n };\n request.onsuccess = function (event) {\n var db = request.result;\n handleDb(db);\n };\n}\nexport { cleanV1 };\n\n//# sourceMappingURL=clean-v1-undefined.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/clean-v1-undefined.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport DBInterface from './db-interface';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport { cleanV1 } from './clean-v1-undefined';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar DB_NAME = 'fcm_token_details_db';\nvar DB_VERSION = 2;\n/** @record */\nfunction ValidateInput() { }\n/** @type {string|undefined} */\nValidateInput.prototype.fcmToken;\n/** @type {string|undefined} */\nValidateInput.prototype.swScope;\n/** @type {string|undefined} */\nValidateInput.prototype.vapidKey;\n/** @type {PushSubscription|undefined} */\nValidateInput.prototype.subscription;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmSenderId;\n/** @type {string|undefined} */\nValidateInput.prototype.fcmPushSet;\nvar TokenDetailsModel = /** @class */ (function (_super) {\n tslib_1.__extends(TokenDetailsModel, _super);\n function TokenDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n TokenDetailsModel.prototype.onDBUpgrade = function (db, evt) {\n if (evt.oldVersion < 1) {\n // New IDB instance\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n }\n if (evt.oldVersion < 2) {\n // Prior to version 2, we were using either 'fcm_token_details_db'\n // or 'undefined' as the database name due to bug in the SDK\n // So remove the old tokens and databases.\n cleanV1();\n }\n };\n /**\n * This method takes an object and will check for known arguments and\n * validate the input.\n * @private\n * @param {!ValidateInput} input\n * @return {!Promise} Returns promise that resolves if input is valid,\n * rejects otherwise.\n */\n TokenDetailsModel.prototype.validateInputs_ = function (input) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (input.fcmToken) {\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN))];\n }\n }\n if (input.swScope) {\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE))];\n }\n }\n if (input.vapidKey) {\n if (!(input.vapidKey instanceof Uint8Array) ||\n input.vapidKey.length !== 65) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY))];\n }\n }\n if (input.subscription) {\n if (!(input.subscription instanceof PushSubscription)) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SUBSCRIPTION))];\n }\n }\n if (input.fcmSenderId) {\n if (typeof input.fcmSenderId !== 'string' ||\n input.fcmSenderId.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID))];\n }\n }\n if (input.fcmPushSet) {\n if (typeof input.fcmPushSet !== 'string' ||\n input.fcmPushSet.length === 0) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.BAD_PUSH_SET))];\n }\n }\n return [2 /*return*/];\n });\n });\n };\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\n var _this = this;\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN));\n }\n return this.validateInputs_({ fcmToken: fcmToken })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Given a service worker scope, this method will look up the details in\n * indexedDB.\n * @public\n * @param {string} swScope\n * @return {Promise} The details associated with that token.\n */\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\n var _this = this;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n return this.validateInputs_({ swScope: swScope })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n var result = event.target.result\n ? event.target.result\n : null;\n resolve(result);\n };\n });\n });\n };\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @param {{swScope: !string, vapidKey: !string,\n * subscription: !PushSubscription, fcmSenderId: !string, fcmToken: !string,\n * fcmPushSet: !string}} input A plain js object containing args to save.\n * @return {Promise}\n */\n TokenDetailsModel.prototype.saveTokenDetails = function (_a) {\n var _this = this;\n var swScope = _a.swScope, vapidKey = _a.vapidKey, subscription = _a.subscription, fcmSenderId = _a.fcmSenderId, fcmToken = _a.fcmToken, fcmPushSet = _a.fcmPushSet;\n if (!swScope) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n if (!vapidKey) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY));\n }\n if (!subscription) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SUBSCRIPTION));\n }\n if (!fcmSenderId) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SENDER_ID));\n }\n if (!fcmToken) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_TOKEN));\n }\n if (!fcmPushSet) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_PUSH_SET));\n }\n return this.validateInputs_({\n swScope: swScope,\n vapidKey: vapidKey,\n subscription: subscription,\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet\n })\n .then(function () {\n return _this.openDatabase();\n })\n .then(function (db) {\n /**\n * @dict\n */\n var details = {\n swScope: swScope,\n vapidKey: arrayBufferToBase64(vapidKey),\n endpoint: subscription.endpoint,\n auth: arrayBufferToBase64(subscription['getKey']('auth')),\n p256dh: arrayBufferToBase64(subscription['getKey']('p256dh')),\n fcmSenderId: fcmSenderId,\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n createTime: Date.now()\n };\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n TokenDetailsModel.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenDetailsModel;\n}(DBInterface));\nexport default TokenDetailsModel;\n\n//# sourceMappingURL=token-details-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/token-details-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport WindowController from './src/controllers/window-controller';\nimport SWController from './src/controllers/sw-controller';\nimport { firebase } from '@firebase/app';\nexport function registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function (app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n // Assume we are in the window context.\n return new WindowController(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: WindowController\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED: 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\n};\nvar ERROR_MAP = (_a = {},\n _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.',\n _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.',\n _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.',\n _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.',\n _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.',\n _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.',\n _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.',\n _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.',\n _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.',\n _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.',\n _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.',\n _a[CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}',\n _a[CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}',\n _a[CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.',\n _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.',\n _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.',\n _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' +\n 'least one character.',\n _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.',\n _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.',\n _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.',\n _a[CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.',\n _a[CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.',\n _a);\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\nvar _a;\n\n//# sourceMappingURL=errors.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/errors.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nvar DBInterface = /** @class */ (function () {\n /**\n * @param {string} dbName\n * @param {number} dbVersion\n */\n function DBInterface(dbName, dbVersion) {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.DB_NAME_ = dbName;\n this.dbVersion_ = dbVersion;\n this.openDbPromise_ = null;\n this.TRANSACTION_READ_WRITE = 'readwrite';\n }\n /**\n * Get the indexedDB as a promsie.\n * @protected\n * @return {!Promise} The IndexedDB database\n */\n DBInterface.prototype.openDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(_this.DB_NAME_, _this.dbVersion_);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n try {\n var db = event.target.result;\n _this.onDBUpgrade(db, event);\n }\n catch (err) {\n // close the database as it can't be used.\n db.close();\n reject(err);\n }\n };\n });\n return this.openDbPromise_;\n };\n /**\n * Close the currently open database.\n * @return {!Promise} Returns the result of the promise chain.\n */\n DBInterface.prototype.closeDatabase = function () {\n var _this = this;\n return Promise.resolve().then(function () {\n if (_this.openDbPromise_) {\n return _this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n });\n };\n /**\n * @protected\n * @param {!IDBDatabase} db\n */\n DBInterface.prototype.onDBUpgrade = function (db, event) {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n return DBInterface;\n}());\nexport default DBInterface;\n\n//# sourceMappingURL=db-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/db-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n]);\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: DEFAULT_PUBLIC_VAPID_KEY\n};\nexport default {\n DEFAULT_PUBLIC_VAPID_KEY: DEFAULT_PUBLIC_VAPID_KEY,\n SUBSCRIPTION_DETAILS: SUBSCRIPTION_DETAILS,\n ENDPOINT: 'https://fcm.googleapis.com'\n // ENDPOINT: 'https://jmt17.google.com'\n};\n\n//# sourceMappingURL=fcm-details.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/fcm-details.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\nvar IIDModel = /** @class */ (function () {\n function IIDModel() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n }\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {Uint8Array} publicVapidKey The public VAPID key.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n IIDModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== FCMDetails.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)\n .then(function (response) { return response.json(); })\n .catch(function () {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED);\n })\n .then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\n * Update the underlying token details for fcmToken.\n */\n IIDModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\n var _this = this;\n var p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n var auth = arrayBufferToBase64(subscription['getKey']('auth'));\n var fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"authorized_entity=\" + senderId + \"&\") +\n (\"endpoint=\" + subscription.endpoint + \"&\") +\n (\"encryption_key=\" + p256dh + \"&\") +\n (\"encryption_auth=\" + auth);\n if (publicVapidKey !== FCMDetails.DEFAULT_PUBLIC_VAPID_KEY) {\n var applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var updateOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUpdateBody\n };\n var updateFetchRes;\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/subscribe', updateOptions)\n .then(function (fetchResponse) {\n updateFetchRes = fetchResponse;\n return fetchResponse.json();\n })\n .catch(function () {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_FAILED);\n })\n .then(function (fcmTokenResponse) {\n if (!updateFetchRes.ok) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UPDATE_NO_TOKEN);\n }\n return fcmTokenResponse['token'];\n });\n };\n /**\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\n */\n IIDModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\n var _this = this;\n var fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" +\n (\"token=\" + fcmToken + \"&\") +\n (\"pushSet=\" + fcmPushSet);\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var unsubscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUnsubscribeBody\n };\n return fetch(FCMDetails.ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions).then(function (fetchResponse) {\n if (!fetchResponse.ok) {\n return fetchResponse.json().then(function (fcmTokenResponse) {\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UNSUBSCRIBE_FAILED, {\n message: message\n });\n }\n }, function (err) {\n throw _this.errorFactory_.create(Errors.codes.TOKEN_UNSUBSCRIBE_FAILED);\n });\n }\n });\n };\n return IIDModel;\n}());\nexport default IIDModel;\n\n//# sourceMappingURL=iid-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/iid-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport DBInterface from './db-interface';\nimport Errors from './errors';\nvar FCM_VAPID_OBJ_STORE = 'fcm_vapid_object_Store';\nvar DB_NAME = 'fcm_vapid_details_db';\nvar DB_VERSION = 1;\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\nvar VapidDetailsModel = /** @class */ (function (_super) {\n tslib_1.__extends(VapidDetailsModel, _super);\n function VapidDetailsModel() {\n return _super.call(this, DB_NAME, DB_VERSION) || this;\n }\n /**\n * @override\n * @param {IDBDatabase} db\n */\n VapidDetailsModel.prototype.onDBUpgrade = function (db) {\n db.createObjectStore(FCM_VAPID_OBJ_STORE, {\n keyPath: 'swScope'\n });\n };\n /**\n * Given a service worker scope, this method will look up the vapid key\n * in indexedDB.\n */\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function () {\n reject(scopeRequest.error);\n };\n scopeRequest.onsuccess = function () {\n var result = scopeRequest.result;\n var vapidKey = null;\n if (result) {\n vapidKey = result.vapidKey;\n }\n resolve(vapidKey);\n };\n });\n });\n };\n /**\n * Save a vapid key against a swScope for later date.\n */\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\n var _this = this;\n if (typeof swScope !== 'string' || swScope.length === 0) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_SCOPE));\n }\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.BAD_VAPID_KEY));\n }\n var details = {\n swScope: swScope,\n vapidKey: vapidKey\n };\n return this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n resolve();\n };\n });\n });\n };\n /**\n * This method deletes details of the current FCM VAPID key for a SW scope.\n * Resolves once the scope/vapid details have been deleted and returns the\n * deleted vapid key.\n */\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\n var _this = this;\n return this.getVapidFromSWScope(swScope).then(function (vapidKey) {\n if (!vapidKey) {\n throw _this.errorFactory_.create(Errors.codes.DELETE_SCOPE_NOT_FOUND);\n }\n return _this.openDatabase().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_VAPID_OBJ_STORE], _this.TRANSACTION_READ_WRITE);\n var objectStore = transaction.objectStore(FCM_VAPID_OBJ_STORE);\n var request = objectStore.delete(swScope);\n request.onerror = function () {\n reject(request.error);\n };\n request.onsuccess = function () {\n if (request.result === 0) {\n reject(_this.errorFactory_.create(Errors.codes.FAILED_DELETE_VAPID_KEY));\n return;\n }\n resolve(vapidKey);\n };\n });\n });\n });\n };\n return VapidDetailsModel;\n}(DBInterface));\nexport default VapidDetailsModel;\n\n//# sourceMappingURL=vapid-details-model.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/vapid-details-model.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport { ErrorFactory } from '@firebase/util';\nimport Errors from '../models/errors';\nimport TokenDetailsModel from '../models/token-details-model';\nimport VapidDetailsModel from '../models/vapid-details-model';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport IIDModel from '../models/iid-model';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\n// Database cache should be invalidated once a week.\nexport var TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\nvar ControllerInterface = /** @class */ (function () {\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenDetailsModel_ = new TokenDetailsModel();\n this.vapidDetailsModel_ = new VapidDetailsModel();\n this.iidModel_ = new IIDModel();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () { return _this.delete(); };\n }\n /**\n * @export\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n var swReg;\n return this.getSWRegistration_()\n .then(function (reg) {\n swReg = reg;\n return _this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);\n })\n .then(function (tokenDetails) {\n if (tokenDetails) {\n return _this.manageExistingToken(tokenDetails, swReg);\n }\n return _this.getNewToken(swReg);\n });\n };\n /**\n * manageExistingToken is triggered if there's an existing FCM token in the\n * database and it can take 3 different actions:\n * 1) Retrieve the existing FCM token from the database.\n * 2) If VAPID details have changed: Delete the existing token and create a\n * new one with the new VAPID key.\n * 3) If the database cache is invalidated: Send a request to FCM to update\n * the token, and to check if the token is still valid on FCM-side.\n */\n ControllerInterface.prototype.manageExistingToken = function (tokenDetails, swReg) {\n var _this = this;\n return this.isTokenStillValid(tokenDetails).then(function (isValid) {\n if (isValid) {\n var now = Date.now();\n if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {\n return tokenDetails['fcmToken'];\n }\n else {\n return _this.updateToken(tokenDetails, swReg);\n }\n }\n else {\n // If the VAPID details are updated, delete the existing token,\n // and create a new one.\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n return _this.getNewToken(swReg);\n });\n }\n });\n };\n /*\n * Checks if the tokenDetails match the details provided in the clients.\n */\n ControllerInterface.prototype.isTokenStillValid = function (tokenDetails) {\n // TODO Validate rest of the details.\n return this.getPublicVapidKey_().then(function (publicKey) {\n if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {\n return false;\n }\n return true;\n });\n };\n ControllerInterface.prototype.updateToken = function (tokenDetails, swReg) {\n var _this = this;\n var publicVapidKey;\n var updatedToken;\n var subscription;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.updateToken(_this.messagingSenderId_, tokenDetails['fcmToken'], tokenDetails['fcmPushSet'], subscription, publicVapidKey);\n })\n .catch(function (err) {\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n })\n .then(function (token) {\n updatedToken = token;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails['fcmPushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return updatedToken;\n });\n };\n ControllerInterface.prototype.getNewToken = function (swReg) {\n var _this = this;\n var publicVapidKey;\n var subscription;\n var tokenDetails;\n return this.getPublicVapidKey_()\n .then(function (publicKey) {\n publicVapidKey = publicKey;\n return _this.getPushSubscription_(swReg, publicVapidKey);\n })\n .then(function (pushSubscription) {\n subscription = pushSubscription;\n return _this.iidModel_.getToken(_this.messagingSenderId_, subscription, publicVapidKey);\n })\n .then(function (iidTokenDetails) {\n tokenDetails = iidTokenDetails;\n var allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n subscription: subscription,\n fcmSenderId: _this.messagingSenderId_,\n fcmToken: tokenDetails['token'],\n fcmPushSet: tokenDetails['pushSet']\n };\n return _this.tokenDetailsModel_.saveTokenDetails(allDetails);\n })\n .then(function () {\n return _this.vapidDetailsModel_.saveVapidDetails(swReg.scope, publicVapidKey);\n })\n .then(function () {\n return tokenDetails['token'];\n });\n };\n /**\n * This method deletes tokens that the token manager looks after,\n * unsubscribes the token from FCM and then unregisters the push\n * subscription if it exists. It returns a promise that indicates\n * whether or not the unsubscribe request was processed successfully.\n * @export\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenDetailsModel_\n .deleteToken(token)\n .then(function (details) {\n return _this.iidModel_.deleteToken(details['fcmSenderId'], details['fcmToken'], details['fcmPushSet']);\n })\n .then(function () {\n return _this.getSWRegistration_()\n .then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n ControllerInterface.prototype.getPublicVapidKey_ = function () {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n ControllerInterface.prototype.getPushSubscription_ = function (registration, publicVapidKey) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!string} b64PublicKey\n */\n ControllerInterface.prototype.usePublicVapidKey = function (b64PublicKey) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\n * @export\n * @param {function(Object)} callback\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n ControllerInterface.prototype.delete = function () {\n return Promise.all([\n this.tokenDetailsModel_.closeDatabase(),\n this.vapidDetailsModel_.closeDatabase()\n ]);\n };\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n ControllerInterface.prototype.getTokenDetailsModel = function () {\n return this.tokenDetailsModel_;\n };\n ControllerInterface.prototype.getVapidDetailsModel = function () {\n return this.vapidDetailsModel_;\n };\n /**\n * @protected\n * @returns {IIDModel}\n */\n ControllerInterface.prototype.getIIDModel = function () {\n return this.iidModel_;\n };\n return ControllerInterface;\n}());\nexport default ControllerInterface;\n\n//# sourceMappingURL=controller-interface.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/controller-interface.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function (msgType, msgData) {\n var message = (_a = {},\n _a[PARAMS.TYPE_OF_MSG] = msgType,\n _a[PARAMS.DATA] = msgData,\n _a);\n return message;\n var _a;\n};\nexport default {\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n};\n\n//# sourceMappingURL=worker-page-message.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/worker-page-message.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n//# sourceMappingURL=default-sw.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/models/default-sw.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport default (function (base64String) {\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\n var base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n var rawData = window.atob(base64);\n var outputArray = new Uint8Array(rawData.length);\n for (var i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n});\n\n//# sourceMappingURL=base64-to-array-buffer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/helpers/base64-to-array-buffer.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport FCMDetails from '../models/fcm-details';\nimport base64ToArrayBuffer from '../helpers/base64-to-array-buffer';\nimport { createSubscribe } from '@firebase/util';\nvar WindowController = /** @class */ (function (_super) {\n tslib_1.__extends(WindowController, _super);\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n _this.messageObserver_ = null;\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n _this.registrationToUse_;\n /**\n * @private\n * @type {Promise}\n */\n _this.manifestCheckPromise_;\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n _this.onMessage_ = createSubscribe(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\n * @private\n * @type {firebase.Observer}\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = createSubscribe(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n }\n else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(function (response) {\n return response.json();\n })\n .catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n })\n .then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(Errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n WindowController.prototype.requestPermission = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib_1.__generator(this, function (_a) {\n if (Notification.permission === NOTIFICATION_PERMISSION.granted) {\n return [2 /*return*/];\n }\n return [2 /*return*/, new Promise(function (resolve, reject) {\n var managePermissionResult = function (result) {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n }\n else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED));\n }\n else {\n return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(managePermissionResult);\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n })];\n });\n });\n };\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\n * This method allows a developer to override the default vapid key\n * and instead use a custom VAPID public key.\n * @export\n * @param {!string} publicKey A URL safe base64 encoded string.\n */\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\n if (typeof publicKey !== 'string') {\n throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);\n }\n if (typeof this.publicVapidKeyToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\n }\n var parsedKey = base64ToArrayBuffer(publicKey);\n if (parsedKey.length !== 65) {\n throw this.errorFactory_.create(Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED);\n }\n this.publicVapidKeyToUse_ = parsedKey;\n };\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function () {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n }\n else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n }\n else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n })\n .then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\n * This will return the default VAPID key or the uint8array version of the public VAPID key\n * provided by the developer.\n * @private\n */\n WindowController.prototype.getPublicVapidKey_ = function () {\n if (this.publicVapidKeyToUse_) {\n return Promise.resolve(this.publicVapidKeyToUse_);\n }\n return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);\n };\n /**\n * Gets a PushSubscription for the current user.\n * @private\n * @param {ServiceWorkerRegistration} registration\n * @return {Promise}\n */\n WindowController.prototype.getPushSubscription_ = function (swRegistration, publicVapidKey) {\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\n };\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n if (_this.messageObserver_) {\n _this.messageObserver_.next(pushMessage);\n }\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n WindowController.prototype.isSupported_ = function () {\n return ('serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey'));\n };\n return WindowController;\n}(ControllerInterface));\nexport default WindowController;\n\n//# sourceMappingURL=window-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/window-controller.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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'use strict';\nimport * as tslib_1 from \"tslib\";\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport FCMDetails from '../models/fcm-details';\nimport WorkerPageMessage from '../models/worker-page-message';\nvar FCM_MSG = 'FCM_MSG';\nvar SWController = /** @class */ (function (_super) {\n tslib_1.__extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) { return _this.onPush_(e); }, false);\n self.addEventListener('pushsubscriptionchange', function (e) { return _this.onSubChange_(e); }, false);\n self.addEventListener('notificationclick', function (e) { return _this.onNotificationClick_(e); }, false);\n /**\n * @private\n * @type {function(Object)|null}\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n }\n catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle_1 = notificationDetails.title || '';\n return _this.getSWRegistration_().then(function (reg) {\n return reg.showNotification(notificationTitle_1, notificationDetails);\n });\n }\n else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\n * @private\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getSWRegistration_()\n .then(function (registration) {\n return registration.pushManager\n .getSubscription()\n .then(function (subscription) {\n // TODO: Check if it's still valid\n // TODO: If not, then update token\n })\n .catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n var tokenDetailsModel = _this.getTokenDetailsModel();\n return tokenDetailsModel\n .getTokenDetailsFromSWScope(registration.scope)\n .then(function (tokenDetails) {\n if (!tokenDetails) {\n // This should rarely occure, but could if indexedDB\n // is corrupted or wiped\n throw err;\n }\n // Attempt to delete the token if we know it's bad\n return _this.deleteToken(tokenDetails['fcmToken']).then(function () {\n throw err;\n });\n });\n });\n })\n .catch(function (err) {\n throw _this.errorFactory_.create(Errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n if (!msgPayload['notification']) {\n // Nothing to do.\n return;\n }\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction)\n .then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient.focus();\n })\n .then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {},\n _a[FCM_MSG] = msgPayload,\n _a);\n return notificationInformation;\n var _a;\n };\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (!callback || typeof callback !== 'function') {\n throw this.errorFactory_.create(Errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url, self.location).href;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url, self.location).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n return suitableClient;\n }\n return null;\n });\n };\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // NOTE: This returns a promise in case this API is abstracted later on to\n // do additional work\n if (!client) {\n return [2 /*return*/, Promise.reject(this.errorFactory_.create(Errors.codes.NO_WINDOW_CLIENT_TO_MSG))];\n }\n client.postMessage(message);\n return [2 /*return*/];\n });\n });\n };\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n return clientList.some(function (client) { return client.visibilityState === 'visible'; });\n });\n };\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(function (clientList) {\n var internalMsg = WorkerPageMessage.createNewMsg(WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n /**\n * This will return the default VAPID key or the uint8array version of the\n * public VAPID key provided by the developer.\n */\n SWController.prototype.getPublicVapidKey_ = function () {\n var _this = this;\n return this.getSWRegistration_()\n .then(function (swReg) {\n return _this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope);\n })\n .then(function (vapidKeyFromDatabase) {\n if (vapidKeyFromDatabase === null) {\n return FCMDetails.DEFAULT_PUBLIC_VAPID_KEY;\n }\n return vapidKeyFromDatabase;\n });\n };\n return SWController;\n}(ControllerInterface));\nexport default SWController;\n\n//# sourceMappingURL=sw-controller.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../messaging/dist/esm/src/controllers/sw-controller.js\n// module id = null\n// module chunks = ","/*!\n * @license Firebase v4.12.0\n * Build: rev-ef14d4f\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([2],{\n\n/***/ 122:\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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__webpack_require__(123);\n\n\n/***/ }),\n\n/***/ 123:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ../app/dist/esm/index.js + 1 modules\nvar esm = __webpack_require__(7);\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/constants.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nvar apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nvar apiUploadBaseUrl = '/v0';\nfunction setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nvar configOption = 'storageBucket';\n/**\n * 1 minute\n */\nvar shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nvar minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/error.js\n/**\n * Copyright 2017 Google Inc.\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\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\n\nvar errors = {};\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nfunction prependCode(code) {\n return 'storage/' + code;\n}\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nfunction bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nfunction projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nfunction invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nfunction error_canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nfunction invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nfunction noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/string.js\n/**\n * Copyright 2017 Google Inc.\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\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw unknown();\n}\nfunction utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nfunction percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar string_DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nfunction dataURLBytes_(string) {\n var parts = new string_DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nfunction dataURLContentType_(string) {\n var parts = new string_DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/taskenums.js\n/**\n * Copyright 2017 Google Inc.\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 */\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/object.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/promise_external.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nfunction make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nfunction promise_external_resolve(value) {\n return Promise.resolve(value);\n}\nfunction promise_external_reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/type.js\n/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nfunction isDef(p) {\n return p != null;\n}\nfunction isJustDef(p) {\n return p !== void 0;\n}\nfunction isFunction(p) {\n return typeof p === 'function';\n}\nfunction isObject(p) {\n return typeof p === 'object';\n}\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio.js\n/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nvar ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhrio_network.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar xhrio_network_NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\n\n\n//# sourceMappingURL=xhrio_network.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/xhriopool.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Factory-like class for creating XhrIo instances.\n */\nvar xhriopool_XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new xhrio_network_NetworkXhrIo();\n };\n return XhrIoPool;\n}());\n\n\n//# sourceMappingURL=xhriopool.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/json.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nfunction jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/location.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\n/**\n * @struct\n */\nvar location_Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\n\n\n//# sourceMappingURL=location.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/path.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nfunction path_parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nfunction child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/url.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/metadata.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\n\nvar mappings_ = null;\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new location_Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/args.js\n/**\n * Copyright 2017 Google Inc.\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\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n }\n else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar args_ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction metadataSpec(opt_optional) {\n return new args_ArgSpec(metadataValidator, opt_optional);\n}\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/fs.js\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nfunction getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/blob.js\n/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\n\n\n\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar blob_FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\n\n\n//# sourceMappingURL=blob.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/array.js\n/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nfunction array_contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nfunction array_clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestinfo.js\nvar RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\n\n\n//# sourceMappingURL=requestinfo.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requests.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = blob_FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array_contains(allowed, status));\n return status;\n}\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nvar resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/observer.js\n/**\n * Copyright 2017 Google Inc.\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/**\n * @struct\n */\nvar observer_Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) ||\n isDef(opt_error) ||\n isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\n\n\n//# sourceMappingURL=observer.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/tasksnapshot.js\nvar UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\n\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/async.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nfunction async_async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promise_external_resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/task.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar task_UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = error_canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) ||\n isJustDef(p['error']) ||\n isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n var observer = new observer_Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n var typeOnly = !(isJustDef(nextOrObserver) ||\n isJustDef(error) ||\n isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = array_clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async_async(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async_async(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async_async(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async_async(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\n\n\n//# sourceMappingURL=task.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/reference.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar reference_Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof location_Location) {\n this.location = location;\n }\n else {\n this.location = location_Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path_parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new location_Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n validate('putString', [\n stringSpec(),\n stringSpec(formatValidator, true),\n metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (isDef(url)) {\n return url;\n }\n else {\n throw noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n return Reference;\n}());\n\n\n//# sourceMappingURL=reference.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/failrequest.js\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar failrequest_FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promise_external_reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\n\n\n//# sourceMappingURL=failrequest.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/requestmap.js\n/**\n * Copyright 2017 Google Inc.\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\n/**\n * @struct\n */\nvar requestmap_RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\n\n\n//# sourceMappingURL=requestmap.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/authwrapper.js\n\n\n\n\n\n\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar authwrapper_AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new requestmap_RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = location_Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n isDef(this.app_.INTERNAL) &&\n isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promise_external_resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new failrequest_FailRequest(appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\n\n\n//# sourceMappingURL=authwrapper.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/backoff.js\n/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nfunction stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/implementation/request.js\n/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\n\n\n\n\n\n\n\n\n/**\n * @struct\n * @template T\n */\nvar request_NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array_contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? appDeleted()\n : error_canceled();\n reject(err);\n }\n else {\n var err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array_contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array_contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nfunction addVersionHeader_(headers) {\n var number = typeof esm[\"default\"] !== 'undefined' ? esm[\"default\"].SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new request_NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/src/service.js\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar service_Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new reference_Reference(authWrapper, loc);\n }\n this.authWrapper_ = new authwrapper_AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = location_Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new location_Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new service_ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n validate('ref', [stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new reference_Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n location_Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new reference_Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\n\n/**\n * @struct\n */\nvar service_ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return promise_external_resolve(undefined);\n };\n return ServiceInternals;\n}());\n\n\n//# sourceMappingURL=service.js.map\n\n// CONCATENATED MODULE: ../storage/dist/esm/index.js\n/* harmony export (immutable) */ __webpack_exports__[\"registerStorage\"] = registerStorage;\n/**\n * Copyright 2017 Google Inc.\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\n\n\n\n\n\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new service_Service(app, new xhriopool_XhrIoPool(), opt_url);\n}\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: service_Service,\n Reference: reference_Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(esm[\"default\"]);\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ })\n\n},[122]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-storage.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-storage.js","/**\n * Copyright 2017 Google Inc.\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\nrequire('@firebase/storage');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./storage/index.js\n// module id = 122\n// module chunks = 2","/**\n * Copyright 2017 Google Inc.\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 */\nimport { configOption } from './constants';\nvar FirebaseStorageError = /** @class */ (function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function () {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function () {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function () {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function () {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}());\nexport { FirebaseStorageError };\nexport var errors = {};\nexport var Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nexport function prependCode(code) {\n return 'storage/' + code;\n}\nexport function unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nexport function objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nexport function bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nexport function projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nexport function quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.');\n}\nexport function unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nexport function unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nexport function retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nexport function invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\");\n}\nexport function canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nexport function invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nexport function invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nexport function invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nexport function noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\");\n}\nexport function cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nexport function serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nexport function noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nexport function invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nexport function invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n }\n else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.');\n}\nexport function appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\");\n}\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n\n//# sourceMappingURL=error.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/error.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nexport var StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nexport function formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n/**\n * @struct\n */\nvar StringData = /** @class */ (function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}());\nexport { StringData };\nexport function dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw errorsExports.unknown();\n}\nexport function utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n }\n else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n }\n else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n }\n else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n }\n else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nexport function percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nexport function base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64: {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL: {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n }\n catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\n * @struct\n */\nvar DataURLParts = /** @class */ (function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}());\nexport function dataURLBytes_(string) {\n var parts = new DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n }\n else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nexport function dataURLContentType_(string) {\n var parts = new DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n\n//# sourceMappingURL=string.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/string.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nexport var TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nexport var InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nexport var TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nexport function taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n//# sourceMappingURL=taskenums.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/taskenums.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains methods for working with objects.\n */\nexport function contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nexport function forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nexport function clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n\n//# sourceMappingURL=object.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/object.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\nexport function make(resolver) {\n return new Promise(resolver);\n}\n/**\n * @template T\n */\nexport function resolve(value) {\n return Promise.resolve(value);\n}\nexport function reject(error) {\n return Promise.reject(error);\n}\n\n//# sourceMappingURL=promise_external.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/promise_external.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef(p) {\n return p != null;\n}\nexport function isJustDef(p) {\n return p !== void 0;\n}\nexport function isFunction(p) {\n return typeof p === 'function';\n}\nexport function isObject(p) {\n return typeof p === 'object';\n}\nexport function isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nexport function isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nexport function isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nexport function isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nexport function isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nexport function isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n\n//# sourceMappingURL=type.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/type.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n }\n catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n }\n else {\n return null;\n }\n}\n\n//# sourceMappingURL=json.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/json.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Contains helper methods for manipulating paths.\n */\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nexport function child(path, childPath) {\n var canonicalChildPath = childPath\n .split('/')\n .filter(function (component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n }\n else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n }\n else {\n return path.slice(index + 1);\n }\n}\n\n//# sourceMappingURL=path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/path.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport * as constants from './constants';\nimport * as object from './object';\nexport function makeNormalUrl(urlPart) {\n return constants.domainBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeDownloadUrl(urlPart) {\n return constants.downloadBase + constants.apiBaseUrl + urlPart;\n}\nexport function makeUploadUrl(urlPart) {\n return constants.domainBase + constants.apiUploadBaseUrl + urlPart;\n}\nexport function makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n object.forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n//# sourceMappingURL=url.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/url.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nexport function noXform_(metadata, value) {\n return value;\n}\n/**\n * @struct\n */\nvar Mapping = /** @class */ (function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}());\nexport { Mapping };\nvar mappings_ = null;\nexport function xformPath(fullPath) {\n var valid = type.isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n }\n else {\n fullPath = fullPath;\n return path.lastComponent(fullPath);\n }\n}\nexport function getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata, size) {\n if (type.isDef(size)) {\n return +size;\n }\n else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata, tokens) {\n var valid = type.isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = UrlUtils.makeDownloadUrl(urlPart);\n var queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nexport function addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nexport function fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nexport function fromResourceString(authWrapper, resourceString, mappings) {\n var obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nexport function toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nexport function metadataValidator(p) {\n var validType = p && type.isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n }\n else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n//# sourceMappingURL=metadata.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/metadata.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as type from './type';\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n }\n catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n }\n else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\n * @struct\n */\nvar ArgSpec = /** @class */ (function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}());\nexport { ArgSpec };\nexport function and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nexport function stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n }\n else {\n validator = stringValidator;\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function metadataSpec(opt_optional) {\n return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);\n}\nexport function nonNegativeNumberSpec() {\n function validator(p) {\n var valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\nexport function looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\nexport function nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\n//# sourceMappingURL=args.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/args.js\n// module id = null\n// module chunks = ","import * as type from './type';\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n }\n else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n }\n else {\n return undefined;\n }\n}\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n }\n else {\n if (type.isNativeBlobDefined()) {\n return new Blob(var_args);\n }\n else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n }\n else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n//# sourceMappingURL=fs.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/fs.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 true if the object is contained in the array (compared with ===).\n * @template T\n */\nexport function contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nexport function clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nexport function remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n//# sourceMappingURL=array.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/array.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as array from './array';\nimport { FbsBlob } from './blob';\nimport * as errorsExports from './error';\nimport * as MetadataUtils from './metadata';\nimport * as object from './object';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn) {\n if (!cndn) {\n throw errorsExports.unknown();\n }\n}\nexport function metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = MetadataUtils.fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nexport function sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = errorsExports.unauthenticated();\n }\n else {\n if (xhr.getStatus() === 402) {\n newErr = errorsExports.quotaExceeded(location.bucket);\n }\n else {\n if (xhr.getStatus() === 403) {\n newErr = errorsExports.unauthorized(location.path);\n }\n else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = errorsExports.objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nexport function getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = UrlUtils.makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) { }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nexport function determineContentType_(metadata, blob) {\n return ((metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream');\n}\nexport function metadataForUpload_(location, blob, opt_metadata) {\n var metadata = object.clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nexport function multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = MetadataUtils.toResourceString(metadata, mappings);\n var preBlobPart = '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nvar ResumableUploadStatus = /** @class */ (function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}());\nexport { ResumableUploadStatus };\nexport function checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n }\n catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array.contains(allowed, status));\n return status;\n}\nexport function createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = UrlUtils.makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = MetadataUtils.toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n }\n catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n }\n catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport var resumableUploadChunkSize = 256 * 1024;\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n }\n else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw errorsExports.serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n }\n else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n//# sourceMappingURL=requests.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requests.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Method for invoking a callback asynchronously.\n */\nimport * as promiseimpl from './promise_external';\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promiseimpl.resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n\n//# sourceMappingURL=async.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/async.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n }\n else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n }\n else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id) {\n id(false);\n}\n\n//# sourceMappingURL=backoff.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/backoff.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\nimport firebase from '@firebase/app';\nimport * as array from './array';\nimport * as backoff from './backoff';\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport * as XhrIoExports from './xhrio';\n/**\n * @struct\n * @template T\n */\nvar NetworkRequest = /** @class */ (function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = promiseimpl.make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\n * Actually starts the retry loop.\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array.contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n }\n else {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n }\n else {\n if (xhr !== null) {\n var err = errorsExports.unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n }\n else {\n reject(err);\n }\n }\n else {\n if (status.canceled) {\n var err = self.appDelete_\n ? errorsExports.appDeleted()\n : errorsExports.canceled();\n reject(err);\n }\n else {\n var err = errorsExports.retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n }\n else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n var isExtraRetryCode = array.contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array.contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}());\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nvar RequestEndStatus = /** @class */ (function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}());\nexport { RequestEndStatus };\nexport function addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nexport function addVersionHeader_(headers) {\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\n * @template T\n */\nexport function makeRequest(requestInfo, authToken, pool) {\n var queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = object.clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n\n//# sourceMappingURL=request.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/request.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport firebase from '@firebase/app';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent } from './src/implementation/taskenums';\nimport { TaskState } from './src/implementation/taskenums';\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\n/**\n * Type constant for Firebase Storage.\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new Service(app, new XhrIoPool(), opt_url);\n}\nexport function registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, \n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(firebase);\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/index.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @enum{number}\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n\n//# sourceMappingURL=xhrio.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Constants used in the Firebase Storage library.\n */\n/**\n * Domain and scheme for API calls.\n */\nexport var domainBase = 'https://firebasestorage.googleapis.com';\n/**\n * Domain and scheme for object downloads.\n */\nexport var downloadBase = 'https://firebasestorage.googleapis.com';\n/**\n * Base URL for non-upload calls to the API.\n */\nexport var apiBaseUrl = '/v0';\n/**\n * Base URL for upload calls to the API.\n */\nexport var apiUploadBaseUrl = '/v0';\nexport function setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nexport var configOption = 'storageBucket';\n/**\n * 1 minute\n */\nexport var shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\n * 2 minutes\n */\nexport var defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\n * 10 minutes\n */\nexport var defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport var minSafeInteger = -9007199254740991;\n\n//# sourceMappingURL=constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/constants.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as XhrIoExports from './xhrio';\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nvar NetworkXhrIo = /** @class */ (function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = XhrIoExports.ErrorCode.NO_ERROR;\n this.sendPromise_ = promiseimpl.make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = XhrIoExports.ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\n * @override\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(opt_headers)) {\n var headers = opt_headers;\n object.forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (type.isDef(opt_body)) {\n this.xhr_.send(opt_body);\n }\n else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n }\n catch (e) {\n return -1;\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\n * Aborts the request.\n * @override\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\n * @override\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}());\nexport { NetworkXhrIo };\n\n//# sourceMappingURL=xhrio_network.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhrio_network.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport { NetworkXhrIo } from './xhrio_network';\n/**\n * Factory-like class for creating XhrIo instances.\n */\nvar XhrIoPool = /** @class */ (function () {\n function XhrIoPool() {\n }\n XhrIoPool.prototype.createXhrIo = function () {\n return new NetworkXhrIo();\n };\n return XhrIoPool;\n}());\nexport { XhrIoPool };\n\n//# sourceMappingURL=xhriopool.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/xhriopool.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\n/**\n * @struct\n */\nvar Location = /** @class */ (function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function () {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n }\n catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n }\n else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n };\n return Location;\n}());\nexport { Location };\n\n//# sourceMappingURL=location.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/location.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport * as string from './string';\nimport { StringFormat } from './string';\nimport * as type from './type';\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nvar FbsBlob = /** @class */ (function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n }\n else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n }\n else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n }\n else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n }\n else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (type.isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n }\n else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (type.isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n }\n else {\n return val;\n }\n });\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n }\n else {\n var uint8Arrays = var_args.map(function (val) {\n if (type.isString(val)) {\n return string.dataFromString(StringFormat.RAW, val).data;\n }\n else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}());\nexport { FbsBlob };\n\n//# sourceMappingURL=blob.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/blob.js\n// module id = null\n// module chunks = ","var RequestInfo = /** @class */ (function () {\n function RequestInfo(url, method, \n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}());\nexport { RequestInfo };\n\n//# sourceMappingURL=requestinfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestinfo.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as type from './type';\n/**\n * @struct\n */\nvar Observer = /** @class */ (function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = type.isFunction(nextOrObserver) ||\n type.isDef(opt_error) ||\n type.isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n }\n else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}());\nexport { Observer };\n\n//# sourceMappingURL=observer.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/observer.js\n// module id = null\n// module chunks = ","var UploadTaskSnapshot = /** @class */ (function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function () {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}());\nexport { UploadTaskSnapshot };\n\n//# sourceMappingURL=tasksnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/tasksnapshot.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines types for interacting with blob transfer tasks.\n */\nimport { InternalTaskState } from './implementation/taskenums';\nimport { Observer } from './implementation/observer';\nimport { TaskEvent, TaskState } from './implementation/taskenums';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport * as fbsArgs from './implementation/args';\nimport * as fbsArray from './implementation/array';\nimport { async as fbsAsync } from './implementation/async';\nimport * as errors from './implementation/error';\nimport * as fbsPromiseimpl from './implementation/promise_external';\nimport * as fbsRequests from './implementation/requests';\nimport * as fbsTaskEnums from './implementation/taskenums';\nimport * as typeUtils from './implementation/type';\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nvar UploadTask = /** @class */ (function () {\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) { metadata = null; }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(errors.Code.CANCELED)) {\n _this.completeTransitions_();\n }\n else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = fbsPromiseimpl.make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () { });\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n }\n else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n }\n else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n }\n else {\n this.continueUpload_();\n }\n }\n }\n }\n else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new fbsRequests.ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n }\n catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }\n else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = fbsRequests.multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = errors.canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function () {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) { nextOrObserver = undefined; }\n if (error === void 0) { error = undefined; }\n if (completed === void 0) { completed = undefined; }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n var nextValidator = fbsArgs.nullFunctionSpec(true).validator;\n var observerValidator = fbsArgs.looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n }\n catch (e) { }\n try {\n observerValidator(p);\n var anyDefined = typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n }\n catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [\n fbsArgs.stringSpec(typeValidator),\n fbsArgs.looseObjectSpec(nextOrObserverValidator, true),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n fbsArgs.validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n fbsArgs.validate('on', specs, arguments);\n }\n var observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [\n fbsArgs.looseObjectSpec(binderNextOrObserverValidator),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n var typeOnly = !(typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n }\n else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n * Adds the given observer.\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\n * Removes the given observer.\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n fbsArray.remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = fbsArray.clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n fbsAsync(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.resume = function () {\n fbsArgs.validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.pause = function () {\n fbsArgs.validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n UploadTask.prototype.cancel = function () {\n fbsArgs.validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}());\nexport { UploadTask };\n\n//# sourceMappingURL=task.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/task.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport * as args from './implementation/args';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as object from './implementation/object';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport * as fbsString from './implementation/string';\nimport { StringFormat } from './implementation/string';\nimport * as type from './implementation/type';\nimport { UploadTask } from './task';\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nvar Reference = /** @class */ (function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof Location) {\n this.location = location;\n }\n else {\n this.location = Location.makeFromUrl(location);\n }\n }\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n Reference.prototype.toString = function () {\n args.validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return metadata.getMappings();\n };\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n Reference.prototype.child = function (childPath) {\n args.validate('child', [args.stringSpec()], arguments);\n var newPath = path.child(this.location.path, childPath);\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get: function () {\n var newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get: function () {\n var location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function () {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function () {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function () {\n return path.lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function () {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) { metadata = null; }\n args.validate('put', [args.uploadDataSpec(), args.metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\n };\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) { format = StringFormat.RAW; }\n args.validate('putString', [\n args.stringSpec(),\n args.stringSpec(fbsString.formatValidator, true),\n args.metadataSpec(true)\n ], arguments);\n this.throwIfRoot_('putString');\n var data = fbsString.dataFromString(format, string);\n var metadata = object.clone(opt_metadata);\n if (!type.isDef(metadata['contentType']) && type.isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\n };\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n Reference.prototype.delete = function () {\n args.validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n Reference.prototype.getMetadata = function () {\n args.validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n Reference.prototype.updateMetadata = function (metadata) {\n args.validate('updateMetadata', [args.metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = requests.updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n Reference.prototype.getDownloadURL = function () {\n args.validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (type.isDef(url)) {\n return url;\n }\n else {\n throw errorsExports.noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n };\n return Reference;\n}());\nexport { Reference };\n\n//# sourceMappingURL=reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/reference.js\n// module id = null\n// module chunks = ","import * as promiseimpl from './promise_external';\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nvar FailRequest = /** @class */ (function () {\n function FailRequest(error) {\n this.promise_ = promiseimpl.reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) { appDelete = false; }\n };\n return FailRequest;\n}());\nexport { FailRequest };\n\n//# sourceMappingURL=failrequest.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/failrequest.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as object from './object';\nimport * as constants from './constants';\n/**\n * @struct\n */\nvar RequestMap = /** @class */ (function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = constants.minSafeInteger;\n }\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\n * Cancels all registered requests.\n */\n RequestMap.prototype.clear = function () {\n object.forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}());\nexport { RequestMap };\n\n//# sourceMappingURL=requestmap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/requestmap.js\n// module id = null\n// module chunks = ","import * as constants from './constants';\nimport * as errorsExports from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport * as promiseimpl from './promise_external';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nvar AuthWrapper = /** @class */ (function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = constants.defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[constants.configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null &&\n type.isDef(this.app_.INTERNAL) &&\n type.isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n }\n else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n }\n else {\n return promiseimpl.resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n }\n else {\n return this.bucket_;\n }\n };\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n }\n else {\n return new FailRequest(errorsExports.appDeleted());\n }\n };\n /**\n * Stop running requests and prevent more from being created.\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}());\nexport { AuthWrapper };\n\n//# sourceMappingURL=authwrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/implementation/authwrapper.js\n// module id = null\n// module chunks = ","/**\n * Copyright 2017 Google Inc.\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 */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as fbsPromiseImpl from './implementation/promise_external';\nimport * as RequestExports from './implementation/request';\nimport { Reference } from './reference';\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nvar Service = /** @class */ (function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(app, maker, RequestExports.makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n }\n else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n }\n else {\n return ref;\n }\n };\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p);\n }\n catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function () {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n args.validate('setMaxUploadRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function () {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n args.validate('setMaxOperationRetryTime', [args.nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function () {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function () {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}());\nexport { Service };\n/**\n * @struct\n */\nvar ServiceInternals = /** @class */ (function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return fbsPromiseImpl.resolve(undefined);\n };\n return ServiceInternals;\n}());\nexport { ServiceInternals };\n\n//# sourceMappingURL=service.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../storage/dist/esm/src/service.js\n// module id = null\n// module chunks = "]} \ No newline at end of file diff --git a/lib/firebase/update.sh b/lib/firebase/update.sh new file mode 100644 index 00000000..2fe6002c --- /dev/null +++ b/lib/firebase/update.sh @@ -0,0 +1,73 @@ +#!/bin/bash +set -ev + +curl -o releases.json https://www.gstatic.com/firebasejs/releases.json + +VERSION=$(node -p "require('./releases.json').current.version") + +echo $VERSION + +get-from-gstatic() { + local file_name="$1"; shift + echo -e "\nDownloading $file_name ..." + if ! curl -O -f "https://www.gstatic.com/firebasejs/$VERSION/$file_name"; then + echo "!!!!! Error downloading v$VERSION of $file_name from gstatic!!!" + exit 1 + fi +} + +SDK_FILES="firebase.js index.d.ts" +SERVICES="app auth database storage messaging firestore functions" +MAPS="app database storage messaging firestore functions" + +for file in $SDK_FILES; do + get-from-gstatic $file +done + +mv index.d.ts firebase.d.ts + +for service in $SERVICES; do + get-from-gstatic "firebase-$service.js" + [ $service != "firestore" ] && [ $service != "functions" ] && get-from-gstatic "firebase-$service-externs.js" +done + +for map in $MAPS; do + get-from-gstatic "firebase-$map.js.map" +done + +get-from-gstatic "firebase.js.map" + +echo "|----- Bumping version number of bower.json to $VERSION... -----|" + +echo "$(node -p "JSON.stringify(Object.assign(require('./bower.json'), { version: '$VERSION' }), null, 2)")" > bower.json + +if [[ $? -ne 0 ]]; then + echo "!!!!! Error: Failed to bump version number of bower.json to $VERSION. !!!!!" + exit 1 +fi + +echo "|----- Pushing the updated code to the firebase/firebase-bower repository... -----|" + +git add . + +if [[ $? -ne 0 ]]; then + echo "!!!!! Error: Failed to do 'git add' from within the firebase-bower directory. !!!!!" + exit 1 +fi + +git commit -m "[firebase-release] Updated Firebase web client to $VERSION" + +if [[ $? -ne 0 ]]; then + echo "!!!!! Error: Failed to do 'git commit' from within the firebase-bower directory. !!!!!" + exit 1 +fi + +git tag -a "v$VERSION" -m "[firebase-release] Updated Firebase web client to $VERSION" + +if [[ $? -ne 0 ]]; then + echo "!!!!! Error: Failed to create git tag from within the firebase-bower directory. !!!!!" + exit 1 +fi + +git push origin master +git push origin "v$VERSION" \ No newline at end of file diff --git a/lib/font-roboto/.bower.json b/lib/font-roboto/.bower.json index 4bb3cb81..c0acfff0 100644 --- a/lib/font-roboto/.bower.json +++ b/lib/font-roboto/.bower.json @@ -1,6 +1,6 @@ { "name": "font-roboto", - "version": "1.0.3", + "version": "1.1.0", "description": "An HTML import for Roboto", "authors": [ "The Polymer Authors" @@ -19,11 +19,11 @@ "ignore": [ "/.*" ], - "_release": "1.0.3", + "_release": "1.1.0", "_resolution": { "type": "version", - "tag": "v1.0.3", - "commit": "6b16584ff654fea05d6bf3e812fb8b225202663f" + "tag": "v1.1.0", + "commit": "014b084ae51314648053e792cf6c870946942953" }, "_source": "https://github.com/PolymerElements/font-roboto.git", "_target": "^1", diff --git a/lib/font-roboto/package-lock.json b/lib/font-roboto/package-lock.json new file mode 100644 index 00000000..0a8f0abd --- /dev/null +++ b/lib/font-roboto/package-lock.json @@ -0,0 +1,987 @@ +{ + "name": "@polymerelements/font-roboto", + "version": "1.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.1.1.tgz", + "integrity": "sha512-rUfH6USpiPYSHl2dC+/rGb3RYK8LPyqNhiuZCLv13F0fhYr01jdTogGuSphEoSLklm1gKRsDsrfZq7OvpzPYEg==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.1", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.10" + }, + "dependencies": { + "@types/node": { + "version": "6.0.97", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.97.tgz", + "integrity": "sha512-k3CDdCq8Uv8AZ7/bmGSSvlwbPDPhkkckSq8Y9ndXowv86m3k07PjG98SigpjVAY9EyHV9kiFldEV306xh4gkig==", + "dev": true + }, + "polymer-analyzer": { + "version": "3.0.0-pre.10", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.10.tgz", + "integrity": "sha1-9vCd15PdL0IomsAdoCb8q6ZfGYw=", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.97", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.0", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "2.3.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "2.2.3", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + } + } + } + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.0" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.0" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.0.tgz", + "integrity": "sha512-zkYho6/4wZyX6o9UQ8rd0ReEaiEYNNCqYFIAACe2Tf9DrYlgzWW27OigYHnnztnnZQwVRpwWmZKegFmDpinIsA==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.0" + } + }, + "@types/winston": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.7.tgz", + "integrity": "sha512-jNhbkxPtt9xbzvihfA0OavjJbpCIyTDSmwE03BVXgCKcz9lwNsq4cg2wsNkY4Av5eH35ttBArhYtVJa6CIrg2A==", + "dev": true, + "requires": { + "@types/node": "9.4.0" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.0.tgz", + "integrity": "sha1-rBriAHC3n248odMmlhMFN3TyDcU=", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.4", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.4" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.4", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", + "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.1.tgz", + "integrity": "sha512-gRJDcIjFSzMcmG/GrJlgL0wWoAxr11mVzCq32bjka0endupm9meLwvoJUKc4HDeFiEIB2X3GvNrhF5cKO4Bd4A==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-2.3.0.tgz", + "integrity": "sha1-+CBJdb0NrLvltYqKk//B/tD/zSo=", + "dev": true, + "requires": { + "@types/clone": "0.1.30", + "@types/node": "6.0.96", + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "2.2.3" + }, + "dependencies": { + "@types/node": { + "version": "6.0.96", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.96.tgz", + "integrity": "sha512-fsOOY6tMQ3jCB2wD51XFDmmpgm4wVKkJECdcVRqapbJEa7awJDcr+SaH8toz+4r4KW8YQ3M7ybXMoSDo1QGewA==", + "dev": true + } + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.4", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", + "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.8" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-2.2.3.tgz", + "integrity": "sha1-DE/EHBAAxea5PUiwP4CDg3g06fY=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.7", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.96", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.96", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.96.tgz", + "integrity": "sha512-fsOOY6tMQ3jCB2wD51XFDmmpgm4wVKkJECdcVRqapbJEa7awJDcr+SaH8toz+4r4KW8YQ3M7ybXMoSDo1QGewA==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/font-roboto/package.json b/lib/font-roboto/package.json index f02f2fb7..a74ad2b7 100644 --- a/lib/font-roboto/package.json +++ b/lib/font-roboto/package.json @@ -14,6 +14,13 @@ "url": "git://github.com/PolymerElements/font-roboto.git" }, "main": "roboto.html", - "license": "http://polymer.github.io/LICENSE.txt", - "homepage": "https://github.com/PolymerElements/font-roboto/" + "license": "BSD-3-Clause", + "homepage": "https://github.com/PolymerElements/font-roboto/", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.1.1", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } } diff --git a/lib/font-roboto/roboto.d.ts b/lib/font-roboto/roboto.d.ts new file mode 100644 index 00000000..12fab1ef --- /dev/null +++ b/lib/font-roboto/roboto.d.ts @@ -0,0 +1,10 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * roboto.html + */ + diff --git a/lib/gold-zip-input/.bower.json b/lib/gold-zip-input/.bower.json index a72e4702..c81f5574 100644 --- a/lib/gold-zip-input/.bower.json +++ b/lib/gold-zip-input/.bower.json @@ -1,6 +1,6 @@ { "name": "gold-zip-input", - "version": "2.0.0", + "version": "2.1.0", "description": "An input field for a zip code", "authors": [ "The Polymer Authors" @@ -54,11 +54,11 @@ } } }, - "_release": "2.0.0", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "4a91d23e9fca9b625a1caf9bde5cf96e794c91b0" + "tag": "v2.1.0", + "commit": "948bbef4ad13417935390d64ab1141b2a7db8532" }, "_source": "https://github.com/PolymerElements/gold-zip-input.git", "_target": "^2.0.0", diff --git a/lib/gold-zip-input/.github/CODEOWNERS b/lib/gold-zip-input/.github/CODEOWNERS new file mode 100644 index 00000000..9ef9eb64 --- /dev/null +++ b/lib/gold-zip-input/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @e111077 +/.travis.yml @azakus diff --git a/lib/gold-zip-input/.gitignore b/lib/gold-zip-input/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/gold-zip-input/.gitignore +++ b/lib/gold-zip-input/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/gold-zip-input/.travis.yml b/lib/gold-zip-input/.travis.yml index 7ad1ba6d..92db200c 100644 --- a/lib/gold-zip-input/.travis.yml +++ b/lib/gold-zip-input/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- diff --git a/lib/gold-zip-input/bower.json b/lib/gold-zip-input/bower.json index 43f48354..c1cf8556 100644 --- a/lib/gold-zip-input/bower.json +++ b/lib/gold-zip-input/bower.json @@ -1,6 +1,6 @@ { "name": "gold-zip-input", - "version": "2.0.0", + "version": "2.1.0", "description": "An input field for a zip code", "authors": [ "The Polymer Authors" diff --git a/lib/gold-zip-input/gold-zip-input.d.ts b/lib/gold-zip-input/gold-zip-input.d.ts new file mode 100644 index 00000000..6206f85d --- /dev/null +++ b/lib/gold-zip-input/gold-zip-input.d.ts @@ -0,0 +1,66 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * gold-zip-input.html + */ + +/// +/// +/// +/// +/// +/// +/// + +/** + * `gold-zip-input` is a single-line text field with Material Design styling + * for entering a US zip code. + * + * + * + * It may include an optional label, which by default is "Zip Code". + * + * + * + * ### Validation + * + * The input supports both 5 digit zip codes (90210) or the full 9 digit ones, + * separated by a dash (90210-9999). + * + * The input can be automatically validated as the user is typing by using + * the `auto-validate` and `required` attributes. For manual validation, the + * element also has a `validate()` method, which returns the validity of the + * input as well sets any appropriate error messages and styles. + * + * See `Polymer.PaperInputBehavior` for more API docs. + * + * ### Styling + * + * See `Polymer.PaperInputContainer` for a list of custom properties used to + * style this element. + */ +interface GoldZipInputElement extends Polymer.Element, Polymer.PaperInputBehavior, Polymer.IronFormElementBehavior { + + /** + * The label for this input. + */ + label: string|null|undefined; + + /** + * Returns a reference to the focusable element. Overridden from PaperInputBehavior + * to correctly focus the native input. + * + */ + readonly _focusableElement: any; + beforeRegister(): void; + _onIronInputReady(): void; + _computeValue(value: any): void; +} + +interface HTMLElementTagNameMap { + "gold-zip-input": GoldZipInputElement; +} diff --git a/lib/gold-zip-input/gold-zip-input.html b/lib/gold-zip-input/gold-zip-input.html index f6758e5f..17f1e5e4 100644 --- a/lib/gold-zip-input/gold-zip-input.html +++ b/lib/gold-zip-input/gold-zip-input.html @@ -130,7 +130,8 @@ inputmode$="[[inputmode]]" placeholder$="[[placeholder]]" readonly$="[[readonly]]" - size$="[[size]]"> + size$="[[size]]" + on-change="_onChange"> diff --git a/lib/gold-zip-input/package-lock.json b/lib/gold-zip-input/package-lock.json new file mode 100644 index 00000000..5b5c7804 --- /dev/null +++ b/lib/gold-zip-input/package-lock.json @@ -0,0 +1,983 @@ +{ + "name": "@polymer/gold-zip-input", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.1", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.1", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.2.0.tgz", + "integrity": "sha512-KEIlhXnIutzKwRbQkGWb/I4HFqBuUykAdHgDED6xqwXJfONCjF5VoE0cXEiurh3XauygxzeDzgtXUqvLkxFzzA==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.1.tgz", + "integrity": "sha512-h3wnflb+jMTipvbbZnClgA2BexrT4w0GcfoCz5qyxd0IRsbqhLSyesM6mqZTAnhbVmhyTm5tuxfRu9R+8l+lGw==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.2.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.3", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.1.tgz", + "integrity": "sha512-6hTjO1NAWkHnDk3OqQ4YrCuwwmGHL9S3nPlzBOUG/R44rda3wLNrfvQ5fkSGjyhHFKM7ALPKcKGrwvCLe0lC7Q==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.6.1" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.3.tgz", + "integrity": "sha512-7Z5PPegwDTyjbaeCnV0efcyS6vdKAU51kpEmS7QFib3P4822l8ICYyMn7qvJnc+WzLoDsuI9gPMKbJ8pCu8XtA==", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.9.0", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.3" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.9.0.tgz", + "integrity": "sha512-WPOqlV2W/M4Ni40QIqYSv8PE7H4rjiPm1KEf02QPtjZOGlAC4Rv7e6UJ1Ke1O70WT5bydcsEn3LViFIqYpVOJw==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.3.tgz", + "integrity": "sha1-Yxvb9xbcyrDmUpGo3CXCMjIIWlI=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/gold-zip-input/package.json b/lib/gold-zip-input/package.json new file mode 100644 index 00000000..25200f37 --- /dev/null +++ b/lib/gold-zip-input/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/gold-zip-input", + "private": true, + "description": "An input field for a zip code", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/gold-zip-input.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/gold-zip-input/zip-validator.d.ts b/lib/gold-zip-input/zip-validator.d.ts new file mode 100644 index 00000000..7796144d --- /dev/null +++ b/lib/gold-zip-input/zip-validator.d.ts @@ -0,0 +1,20 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * zip-validator.html + */ + +/// +/// + +interface ZipValidatorElement extends Polymer.Element, Polymer.IronValidatorBehavior { + validate(value: any): any; +} + +interface HTMLElementTagNameMap { + "zip-validator": ZipValidatorElement; +} diff --git a/lib/iron-a11y-announcer/.bower.json b/lib/iron-a11y-announcer/.bower.json index 5b206b85..94117531 100644 --- a/lib/iron-a11y-announcer/.bower.json +++ b/lib/iron-a11y-announcer/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-a11y-announcer", - "version": "2.0.0", + "version": "2.1.0", "description": "A singleton element that simplifies announcing text to screen readers.", "keywords": [ "web-components", @@ -53,11 +53,11 @@ "webcomponentsjs": "^1.0.0" }, "homepage": "https://github.com/PolymerElements/iron-a11y-announcer", - "_release": "2.0.0", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "d87178289c267b3c80c2dbd0060cb7ba9804bf53" + "tag": "v2.1.0", + "commit": "7e2c529fcb96582cb8c13905896fcf8496763966" }, "_source": "https://github.com/PolymerElements/iron-a11y-announcer.git", "_target": "^2.0.0", diff --git a/lib/iron-a11y-announcer/.github/CODEOWNERS b/lib/iron-a11y-announcer/.github/CODEOWNERS new file mode 100644 index 00000000..cc86f1ec --- /dev/null +++ b/lib/iron-a11y-announcer/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @notwaldorf +/.travis.yml @azakus diff --git a/lib/iron-a11y-announcer/.gitignore b/lib/iron-a11y-announcer/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-a11y-announcer/.gitignore +++ b/lib/iron-a11y-announcer/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-a11y-announcer/.travis.yml b/lib/iron-a11y-announcer/.travis.yml index a408fcae..d13ba205 100644 --- a/lib/iron-a11y-announcer/.travis.yml +++ b/lib/iron-a11y-announcer/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- diff --git a/lib/iron-a11y-announcer/iron-a11y-announcer.d.ts b/lib/iron-a11y-announcer/iron-a11y-announcer.d.ts new file mode 100644 index 00000000..e777c372 --- /dev/null +++ b/lib/iron-a11y-announcer/iron-a11y-announcer.d.ts @@ -0,0 +1,68 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-a11y-announcer.html + */ + +/// + +declare namespace Polymer { + + /** + * `iron-a11y-announcer` is a singleton element that is intended to add a11y + * to features that require on-demand announcement from screen readers. In + * order to make use of the announcer, it is best to request its availability + * in the announcing element. + * + * Example: + * + * Polymer({ + * + * is: 'x-chatty', + * + * attached: function() { + * // This will create the singleton element if it has not + * // been created yet: + * Polymer.IronA11yAnnouncer.requestAvailability(); + * } + * }); + * + * After the `iron-a11y-announcer` has been made available, elements can + * make announces by firing bubbling `iron-announce` events. + * + * Example: + * + * this.fire('iron-announce', { + * text: 'This is an announcement!' + * }, { bubbles: true }); + * + * Note: announcements are only audible if you have a screen reader enabled. + */ + class IronA11yAnnouncer extends Polymer.Element { + + /** + * The value of mode is used to set the `aria-live` attribute + * for the element that will be announced. Valid values are: `off`, + * `polite` and `assertive`. + */ + mode: string|null|undefined; + _text: string|null|undefined; + created(): void; + + /** + * Cause a text string to be announced by screen readers. + * + * @param text The text that should be announced. + */ + announce(text: string): void; + _onIronAnnounce(event: any): void; + } +} + +interface HTMLElementTagNameMap { + "iron-a11y-announcer": Polymer.IronA11yAnnouncer; +} diff --git a/lib/iron-a11y-announcer/package-lock.json b/lib/iron-a11y-announcer/package-lock.json new file mode 100644 index 00000000..51a44e05 --- /dev/null +++ b/lib/iron-a11y-announcer/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "@polymer/iron-a11y-announcer", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-a11y-announcer/package.json b/lib/iron-a11y-announcer/package.json new file mode 100644 index 00000000..ee95f424 --- /dev/null +++ b/lib/iron-a11y-announcer/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-a11y-announcer", + "private": true, + "description": "A singleton element that simplifies announcing text to screen readers.", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-a11y-announcer.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-a11y-keys-behavior/.bower.json b/lib/iron-a11y-keys-behavior/.bower.json index 5388ae4b..1e2b7287 100644 --- a/lib/iron-a11y-keys-behavior/.bower.json +++ b/lib/iron-a11y-keys-behavior/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-a11y-keys-behavior", - "version": "2.0.1", + "version": "2.1.0", "description": "A behavior that enables keybindings for greater a11y.", "keywords": [ "web-components", @@ -52,11 +52,11 @@ "webcomponentsjs": "^1.0.0" }, "homepage": "https://github.com/PolymerElements/iron-a11y-keys-behavior", - "_release": "2.0.1", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.1", - "commit": "a3f03fc3fb5a0d8e93eaa33c2b6c02c16098b402" + "tag": "v2.1.0", + "commit": "b6c34e5b7e1876bcf1a6b6b18915c83d43c8bcb9" }, "_source": "https://github.com/PolymerElements/iron-a11y-keys-behavior.git", "_target": "^2.0.1", diff --git a/lib/iron-a11y-keys-behavior/.github/CODEOWNERS b/lib/iron-a11y-keys-behavior/.github/CODEOWNERS new file mode 100644 index 00000000..c5097c0c --- /dev/null +++ b/lib/iron-a11y-keys-behavior/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @valdrinkoshi +/.travis.yml @azakus diff --git a/lib/iron-a11y-keys-behavior/.gitignore b/lib/iron-a11y-keys-behavior/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-a11y-keys-behavior/.gitignore +++ b/lib/iron-a11y-keys-behavior/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-a11y-keys-behavior/.travis.yml b/lib/iron-a11y-keys-behavior/.travis.yml index 3ac95a1d..ef5fc675 100644 --- a/lib/iron-a11y-keys-behavior/.travis.yml +++ b/lib/iron-a11y-keys-behavior/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g bower polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- @@ -19,5 +23,7 @@ addons: - google-chrome-stable script: - xvfb-run polymer test - - 'if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then polymer test -s ''default''; fi' + - >- + if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then polymer test -s 'default'; + fi dist: trusty diff --git a/lib/iron-a11y-keys-behavior/iron-a11y-keys-behavior.d.ts b/lib/iron-a11y-keys-behavior/iron-a11y-keys-behavior.d.ts new file mode 100644 index 00000000..180d1288 --- /dev/null +++ b/lib/iron-a11y-keys-behavior/iron-a11y-keys-behavior.d.ts @@ -0,0 +1,104 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-a11y-keys-behavior.html + */ + +/// + +declare namespace Polymer { + + /** + * `Polymer.IronA11yKeysBehavior` provides a normalized interface for processing + * keyboard commands that pertain to [WAI-ARIA best practices](http://www.w3.org/TR/wai-aria-practices/#kbd_general_binding). + * The element takes care of browser differences with respect to Keyboard events + * and uses an expressive syntax to filter key presses. + * + * Use the `keyBindings` prototype property to express what combination of keys + * will trigger the callback. A key binding has the format + * `"KEY+MODIFIER:EVENT": "callback"` (`"KEY": "callback"` or + * `"KEY:EVENT": "callback"` are valid as well). Some examples: + * + * keyBindings: { + * 'space': '_onKeydown', // same as 'space:keydown' + * 'shift+tab': '_onKeydown', + * 'enter:keypress': '_onKeypress', + * 'esc:keyup': '_onKeyup' + * } + * + * The callback will receive with an event containing the following information in `event.detail`: + * + * _onKeydown: function(event) { + * console.log(event.detail.combo); // KEY+MODIFIER, e.g. "shift+tab" + * console.log(event.detail.key); // KEY only, e.g. "tab" + * console.log(event.detail.event); // EVENT, e.g. "keydown" + * console.log(event.detail.keyboardEvent); // the original KeyboardEvent + * } + * + * Use the `keyEventTarget` attribute to set up event handlers on a specific + * node. + * + * See the [demo source code](https://github.com/PolymerElements/iron-a11y-keys-behavior/blob/master/demo/x-key-aware.html) + * for an example. + */ + interface IronA11yKeysBehavior { + + /** + * The EventTarget that will be firing relevant KeyboardEvents. Set it to + * `null` to disable the listeners. + */ + keyEventTarget: EventTarget|null; + + /** + * If true, this property will cause the implementing element to + * automatically stop propagation on any handled KeyboardEvents. + */ + stopKeyboardEventPropagation: boolean|null|undefined; + _boundKeyHandlers: any[]|null|undefined; + + /** + * own properties of everything on the "prototype". + */ + _imperativeKeyBindings: object|null|undefined; + + /** + * To be used to express what combination of keys will trigger the relative + * callback. e.g. `keyBindings: { 'esc': '_onEscPressed'}` + */ + keyBindings: object; + registered(): void; + attached(): void; + detached(): void; + + /** + * Can be used to imperatively add a key binding to the implementing + * element. This is the imperative equivalent of declaring a keybinding + * in the `keyBindings` prototype property. + */ + addOwnKeyBinding(eventString: string, handlerName: string): void; + + /** + * When called, will remove all imperatively-added key bindings. + */ + removeOwnKeyBindings(): void; + + /** + * Returns true if a keyboard event matches `eventString`. + */ + keyboardEventMatchesKeys(event: KeyboardEvent|null, eventString: string): boolean; + _collectKeyBindings(): any; + _prepKeyBindings(): void; + _addKeyBinding(eventString: any, handlerName: any): void; + _resetKeyEventListeners(): void; + _listenKeyEventListeners(): void; + _unlistenKeyEventListeners(): void; + _onKeyBindingEvent(keyBindings: any, event: any): void; + _triggerKeyHandler(keyCombo: any, handlerName: any, keyboardEvent: any): void; + } + + const IronA11yKeysBehavior: object; +} diff --git a/lib/iron-a11y-keys-behavior/package-lock.json b/lib/iron-a11y-keys-behavior/package-lock.json new file mode 100644 index 00000000..6efc6c14 --- /dev/null +++ b/lib/iron-a11y-keys-behavior/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "@polymer/iron-a11y-keys-behavior", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-a11y-keys-behavior/package.json b/lib/iron-a11y-keys-behavior/package.json new file mode 100644 index 00000000..f30e825c --- /dev/null +++ b/lib/iron-a11y-keys-behavior/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-a11y-keys-behavior", + "private": true, + "description": "A behavior that enables keybindings for greater a11y.", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-a11y-keys-behavior.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-a11y-keys/.bower.json b/lib/iron-a11y-keys/.bower.json index efd15068..a43e49ec 100644 --- a/lib/iron-a11y-keys/.bower.json +++ b/lib/iron-a11y-keys/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-a11y-keys", - "version": "2.0.0", + "version": "2.1.1", "description": "A basic element implementation of iron-a11y-keys-behavior, matching the legacy core-a11y-keys.", "keywords": [ "web-components", @@ -52,11 +52,11 @@ "webcomponentsjs": "^1.0.0" }, "homepage": "https://github.com/PolymerElements/iron-a11y-keys", - "_release": "2.0.0", + "_release": "2.1.1", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "27f4f48935c741f4eb49d7a1ded697ea0452acf4" + "tag": "v2.1.1", + "commit": "b037b6270a66b67af554b675453d03b3789e2e93" }, "_source": "https://github.com/PolymerElements/iron-a11y-keys.git", "_target": "^2.0.0", diff --git a/lib/iron-a11y-keys/.github/CODEOWNERS b/lib/iron-a11y-keys/.github/CODEOWNERS new file mode 100644 index 00000000..c5097c0c --- /dev/null +++ b/lib/iron-a11y-keys/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @valdrinkoshi +/.travis.yml @azakus diff --git a/lib/iron-a11y-keys/.gitignore b/lib/iron-a11y-keys/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-a11y-keys/.gitignore +++ b/lib/iron-a11y-keys/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-a11y-keys/.travis.yml b/lib/iron-a11y-keys/.travis.yml index 82266b7b..45cc9cb6 100644 --- a/lib/iron-a11y-keys/.travis.yml +++ b/lib/iron-a11y-keys/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g bower polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- @@ -19,5 +23,7 @@ addons: - google-chrome-stable script: - xvfb-run polymer test - - 'if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then polymer test -s ''default''; fi' + - >- + if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then polymer test -s 'default'; + fi dist: trusty diff --git a/lib/iron-a11y-keys/README.md b/lib/iron-a11y-keys/README.md index ede22543..bb937c56 100644 --- a/lib/iron-a11y-keys/README.md +++ b/lib/iron-a11y-keys/README.md @@ -110,7 +110,7 @@ practices](http://www.w3.org/TR/wai-aria-practices/#slider): on-keys-pressed="increment"> - ``` diff --git a/lib/iron-a11y-keys/bower.json b/lib/iron-a11y-keys/bower.json index 62ceb484..9d8f1914 100644 --- a/lib/iron-a11y-keys/bower.json +++ b/lib/iron-a11y-keys/bower.json @@ -1,6 +1,6 @@ { "name": "iron-a11y-keys", - "version": "2.0.0", + "version": "2.1.1", "description": "A basic element implementation of iron-a11y-keys-behavior, matching the legacy core-a11y-keys.", "keywords": [ "web-components", diff --git a/lib/iron-a11y-keys/iron-a11y-keys.d.ts b/lib/iron-a11y-keys/iron-a11y-keys.d.ts new file mode 100644 index 00000000..dc91ca4c --- /dev/null +++ b/lib/iron-a11y-keys/iron-a11y-keys.d.ts @@ -0,0 +1,32 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-a11y-keys.html + */ + +/// +/// + +interface IronA11yKeysElement extends Polymer.Element, Polymer.IronA11yKeysBehavior { + target: Node|null; + + /** + * Space delimited list of keys where each key follows the format: + * `[MODIFIER+]*KEY[:EVENT]`. + * e.g. `keys="space ctrl+shift+tab enter:keyup"`. + * More detail can be found in the "Grammar" section of the documentation + */ + keys: string|null|undefined; + attached(): void; + _targetChanged(target: any): void; + _keysChanged(): void; + _fireKeysPressed(event: any): void; +} + +interface HTMLElementTagNameMap { + "iron-a11y-keys": IronA11yKeysElement; +} diff --git a/lib/iron-a11y-keys/package-lock.json b/lib/iron-a11y-keys/package-lock.json new file mode 100644 index 00000000..2fdee71d --- /dev/null +++ b/lib/iron-a11y-keys/package-lock.json @@ -0,0 +1,1196 @@ +{ + "name": "@polymer/iron-a11y-keys", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.1.tgz", + "integrity": "sha512-N0rNp+F8Cp0iQ40i3Lx3onWnRXMnfMosR9WFE+IHMF4k5Fv2toRYz77EZMEPPZCz1tzFmCUelHxvxpdssT9oCw==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.1", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "5.0.2", + "doctrine": "2.1.0", + "escodegen": "1.9.1", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.14" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.2.0.tgz", + "integrity": "sha512-KEIlhXnIutzKwRbQkGWb/I4HFqBuUykAdHgDED6xqwXJfONCjF5VoE0cXEiurh3XauygxzeDzgtXUqvLkxFzzA==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.1.tgz", + "integrity": "sha512-h3wnflb+jMTipvbbZnClgA2BexrT4w0GcfoCz5qyxd0IRsbqhLSyesM6mqZTAnhbVmhyTm5tuxfRu9R+8l+lGw==", + "dev": true, + "requires": { + "@types/node": "9.4.7" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.2.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.7" + } + }, + "@types/is-windows": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@types/is-windows/-/is-windows-0.2.0.tgz", + "integrity": "sha1-byTuSHMdMRaOpRBhDW3RXl/Jxv8=", + "dev": true + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.7.tgz", + "integrity": "sha512-4Ba90mWNx8ddbafuyGGwjkZMigi+AWfYLSDCpovwsE63ia8w93r3oJ8PIAQc3y8U+XHcnMOHPIzNe3o438Ywcw==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.7" + } + }, + "@types/resolve": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.6.tgz", + "integrity": "sha512-g+Rg8uMWY76oYTyaL+m7ZcblqF/oj7pE6uEUyACluJx4zcop1Lk14qQiocdEkEVMDFm6DmKpxJhsER+ZuTwG3g==", + "dev": true, + "requires": { + "@types/node": "9.4.7" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.7" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "1.9.1" + } + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-7.0.0-beta.3.tgz", + "integrity": "sha512-flMsJ9eSpShupt2Gwpka84DoMePvE4HlDObzdEc+1iNkacv3+NHlsJ7dMKmbnVA/AT22UhcGEBHwbJLoXWBO6Q==", + "dev": true, + "requires": { + "chalk": "2.3.2", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + }, + "dependencies": { + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "babel-helper-function-name": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-helper-function-name/-/babel-helper-function-name-7.0.0-beta.3.tgz", + "integrity": "sha512-iMWYqwDarQOVlEGcK1MfbtK9vrFGs5Z4UQsdASJUHdhBp918EM5kndwriiIbhUX8gr2B/CEV/udJkFTrHsjdMQ==", + "dev": true, + "requires": { + "babel-helper-get-function-arity": "7.0.0-beta.3", + "babel-template": "7.0.0-beta.3", + "babel-traverse": "7.0.0-beta.3", + "babel-types": "7.0.0-beta.3" + } + }, + "babel-helper-get-function-arity": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-helper-get-function-arity/-/babel-helper-get-function-arity-7.0.0-beta.3.tgz", + "integrity": "sha512-ZkYFRMWKx1c9fUW72YNM3eieBG701CMbLjmLLWmJTTPc0F0kddS9Fwok26EAmndUAgD6kFdh7ms3PH94MdGuGQ==", + "dev": true, + "requires": { + "babel-types": "7.0.0-beta.3" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-template": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-7.0.0-beta.3.tgz", + "integrity": "sha512-urJduLja89kSDGqY8ryw8iIwQnMl30IvhMtMNmDD7vBX0l0oylaLgK+7df/9ODX9vR/PhXuif6HYl5HlzAKXMg==", + "dev": true, + "requires": { + "babel-code-frame": "7.0.0-beta.3", + "babel-traverse": "7.0.0-beta.3", + "babel-types": "7.0.0-beta.3", + "babylon": "7.0.0-beta.27", + "lodash": "4.17.5" + }, + "dependencies": { + "babylon": { + "version": "7.0.0-beta.27", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.27.tgz", + "integrity": "sha512-ksRx+r8eFIfdt63MCgLc9VxGL7W3jcyveQvMpNMVHgW+eb9mq3Xbm45FLCNkw8h92RvoNp4uuiwzcCEwxjDBZg==", + "dev": true + } + } + }, + "babel-traverse": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-7.0.0-beta.3.tgz", + "integrity": "sha512-xyh/aPYuedMAfQlSj2kjHjsEmY5/Dpxs576L05DySAVMrV+ADX6l4mTOLysAEGwJfkePJlDLhFuS6SKaxv1V7w==", + "dev": true, + "requires": { + "babel-code-frame": "7.0.0-beta.3", + "babel-helper-function-name": "7.0.0-beta.3", + "babel-types": "7.0.0-beta.3", + "babylon": "7.0.0-beta.27", + "debug": "3.1.0", + "globals": "10.4.0", + "invariant": "2.2.3", + "lodash": "4.17.5" + }, + "dependencies": { + "babylon": { + "version": "7.0.0-beta.27", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.27.tgz", + "integrity": "sha512-ksRx+r8eFIfdt63MCgLc9VxGL7W3jcyveQvMpNMVHgW+eb9mq3Xbm45FLCNkw8h92RvoNp4uuiwzcCEwxjDBZg==", + "dev": true + } + } + }, + "babel-types": { + "version": "7.0.0-beta.3", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-7.0.0-beta.3.tgz", + "integrity": "sha512-36k8J+byAe181OmCMawGhw+DtKO7AwexPVtsPXoMfAkjtZgoCX3bEuHWfdE5sYxRM8dojvtG/+O08M0Z/YDC6w==", + "dev": true, + "requires": { + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "2.0.0" + }, + "dependencies": { + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + } + } + }, + "babylon": { + "version": "7.0.0-beta.40", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.40.tgz", + "integrity": "sha512-AVxF2EcxvGD5hhOuLTOLAXBb0VhwWpEX0HyHdAI2zU+AAP4qEwtQj8voz1JR3uclGai0rfcE+dCTHnNMOnimFg==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "cancel-token": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/cancel-token/-/cancel-token-0.1.1.tgz", + "integrity": "sha1-wYGXZ0uxyEwdaTPr8V2NWlznm08=", + "dev": true, + "requires": { + "@types/node": "4.2.23" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "chalk": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", + "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", + "dev": true, + "requires": { + "ansi-styles": "3.2.1", + "escape-string-regexp": "1.0.5", + "supports-color": "5.3.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "color-convert": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", + "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-5.0.2.tgz", + "integrity": "sha512-hICrJJ5zUI7hnEBBluE2169CG3Xnn4D5HPeLkMjbiOyneSLTUX5Wz1d4FSi3xALUtzulIBStSt0S2tLXs8eVrg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "chalk": "2.3.2", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.1.tgz", + "integrity": "sha512-6hTjO1NAWkHnDk3OqQ4YrCuwwmGHL9S3nPlzBOUG/R44rda3wLNrfvQ5fkSGjyhHFKM7ALPKcKGrwvCLe0lC7Q==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.6.1" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-10.4.0.tgz", + "integrity": "sha512-uNUtxIZpGyuaq+5BqGGQHsL4wUlJAXRqOm6g3Y48/CWNGTLONgBibI0lh6lGxjR2HljFYUfszb+mk4WkgMntsA==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.3.tgz", + "integrity": "sha512-7Z5PPegwDTyjbaeCnV0efcyS6vdKAU51kpEmS7QFib3P4822l8ICYyMn7qvJnc+WzLoDsuI9gPMKbJ8pCu8XtA==", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-parse": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", + "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.1" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.14", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.14.tgz", + "integrity": "sha512-1Zh/smUWMrjBB7NFUk8i7EAnjO81PqhI0/RzMMy9VgAbPQ6jOROwFX71T02CgpkZYa0O66Ybl7G3+4+0S1aF1Q==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/is-windows": "0.2.0", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.102", + "@types/parse5": "2.2.34", + "@types/resolve": "0.0.6", + "babel-generator": "6.26.1", + "babel-traverse": "7.0.0-beta.3", + "babel-types": "7.0.0-beta.3", + "babylon": "7.0.0-beta.40", + "cancel-token": "0.1.1", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "is-windows": "1.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "path-is-inside": "1.0.2", + "polymer-project-config": "3.9.0", + "resolve": "1.5.0", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.3", + "whatwg-url": "6.4.0" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.102", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.102.tgz", + "integrity": "sha512-EhNufyBoC1Kqaj+XMHGzi6mPUC8wVABOMTPE5XaSJc49LIVvXsyrV1HYMAPTUViT7E4wLUB38OdDmb+HshjGmA==", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.9.0.tgz", + "integrity": "sha512-WPOqlV2W/M4Ni40QIqYSv8PE7H4rjiPm1KEf02QPtjZOGlAC4Rv7e6UJ1Ke1O70WT5bydcsEn3LViFIqYpVOJw==", + "dev": true, + "requires": { + "@types/node": "6.0.102", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.102", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.102.tgz", + "integrity": "sha512-EhNufyBoC1Kqaj+XMHGzi6mPUC8wVABOMTPE5XaSJc49LIVvXsyrV1HYMAPTUViT7E4wLUB38OdDmb+HshjGmA==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "punycode": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.0.tgz", + "integrity": "sha1-X4Y+3Im5bbCQdLrXlHvwkFbKTn0=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "resolve": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.5.0.tgz", + "integrity": "sha512-hgoSGrc3pjzAPHNBg+KnFcK2HwlHTs/YrAGUr6qgTVUZmXv1UEXXl0bZNBKMA9fud6lRYFdPGz0xXxycPzmmiw==", + "dev": true, + "requires": { + "path-parse": "1.0.5" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.3.0.tgz", + "integrity": "sha512-0aP01LLIskjKs3lq52EC0aGBAJhLq7B2Rd8HC/DR/PtNNpcLilNmHC12O+hu0usQpo7wtHNRqtrhBwtDb0+dNg==", + "dev": true, + "requires": { + "has-flag": "3.0.0" + } + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "dev": true, + "requires": { + "punycode": "2.1.0" + } + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.3.tgz", + "integrity": "sha1-Yxvb9xbcyrDmUpGo3CXCMjIIWlI=", + "dev": true + }, + "webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true + }, + "whatwg-url": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.4.0.tgz", + "integrity": "sha512-Z0CVh/YE217Foyb488eo+iBv+r7eAQ0wSTyApi9n06jhcA3z6Nidg/EGvl0UFkg7kMdKxfBzzr+o9JF+cevgMg==", + "dev": true, + "requires": { + "lodash.sortby": "4.7.0", + "tr46": "1.0.1", + "webidl-conversions": "4.0.2" + } + }, + "winston": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.1.tgz", + "integrity": "sha512-k/+Dkzd39ZdyJHYkuaYmf4ff+7j+sCIy73UCOWHYA67/WXU+FF/Y6PF28j+Vy7qNRPHWO+dR+/+zkoQWPimPqg==", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-a11y-keys/package.json b/lib/iron-a11y-keys/package.json new file mode 100644 index 00000000..679dc82d --- /dev/null +++ b/lib/iron-a11y-keys/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-a11y-keys", + "private": true, + "description": "A basic element implementation of iron-a11y-keys-behavior, matching the legacy core-a11y-keys.", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-a11y-keys.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.1", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-ajax/.bower.json b/lib/iron-ajax/.bower.json index 4d632aee..d4dbf5c8 100644 --- a/lib/iron-ajax/.bower.json +++ b/lib/iron-ajax/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-ajax", - "version": "2.0.6", + "version": "2.1.3", "description": "Makes it easy to make ajax calls and parse the response", "private": true, "authors": [ @@ -53,11 +53,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "2.0.6", + "_release": "2.1.3", "_resolution": { "type": "version", - "tag": "v2.0.6", - "commit": "db9535a8e40795b464679469f5b3dd71b9163def" + "tag": "v2.1.3", + "commit": "923e2b523832b2b7ff8768afbbec695f87a2dfd7" }, "_source": "https://github.com/PolymerElements/iron-ajax.git", "_target": "^2.0.6", diff --git a/lib/iron-ajax/.github/CODEOWNERS b/lib/iron-ajax/.github/CODEOWNERS new file mode 100644 index 00000000..9ef9eb64 --- /dev/null +++ b/lib/iron-ajax/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @e111077 +/.travis.yml @azakus diff --git a/lib/iron-ajax/.gitignore b/lib/iron-ajax/.gitignore index 1b3dfde0..678c29bf 100644 --- a/lib/iron-ajax/.gitignore +++ b/lib/iron-ajax/.gitignore @@ -1,2 +1,3 @@ bower_components* -bower-*.json \ No newline at end of file +bower-*.json +node_modules diff --git a/lib/iron-ajax/.travis.yml b/lib/iron-ajax/.travis.yml index e0f2d61c..bb1aefa3 100644 --- a/lib/iron-ajax/.travis.yml +++ b/lib/iron-ajax/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- diff --git a/lib/iron-ajax/bower.json b/lib/iron-ajax/bower.json index 30aa3083..f59705eb 100644 --- a/lib/iron-ajax/bower.json +++ b/lib/iron-ajax/bower.json @@ -1,6 +1,6 @@ { "name": "iron-ajax", - "version": "2.0.6", + "version": "2.1.3", "description": "Makes it easy to make ajax calls and parse the response", "private": true, "authors": [ diff --git a/lib/iron-ajax/iron-ajax.d.ts b/lib/iron-ajax/iron-ajax.d.ts new file mode 100644 index 00000000..301d134b --- /dev/null +++ b/lib/iron-ajax/iron-ajax.d.ts @@ -0,0 +1,261 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-ajax.html + */ + +/// +/// + +/** + * The `iron-ajax` element exposes network request functionality. + * + * + * + * With `auto` set to `true`, the element performs a request whenever + * its `url`, `params` or `body` properties are changed. Automatically generated + * requests will be debounced in the case that multiple attributes are changed + * sequentially. + * + * Note: The `params` attribute must be double quoted JSON. + * + * You can trigger a request explicitly by calling `generateRequest` on the + * element. + */ +interface IronAjaxElement extends Polymer.Element { + + /** + * The URL target of the request. + */ + url: string|null|undefined; + + /** + * An object that contains query parameters to be appended to the + * specified `url` when generating a request. If you wish to set the body + * content when making a POST request, you should use the `body` property + * instead. + */ + params: object|null|undefined; + + /** + * The HTTP method to use such as 'GET', 'POST', 'PUT', or 'DELETE'. + * Default is 'GET'. + */ + method: string|null|undefined; + + /** + * HTTP request headers to send. + * + * Example: + * + * + * + * Note: setting a `Content-Type` header here will override the value + * specified by the `contentType` property of this element. + */ + headers: object|null|undefined; + + /** + * Content type to use when sending data. If the `contentType` property + * is set and a `Content-Type` header is specified in the `headers` + * property, the `headers` property value will take precedence. + * + * Varies the handling of the `body` param. + */ + contentType: string|null|undefined; + + /** + * Body content to send with the request, typically used with "POST" + * requests. + * + * If body is a string it will be sent unmodified. + * + * If Content-Type is set to a value listed below, then + * the body will be encoded accordingly. + * + * * `content-type="application/json"` + * * body is encoded like `{"foo":"bar baz","x":1}` + * * `content-type="application/x-www-form-urlencoded"` + * * body is encoded like `foo=bar+baz&x=1` + * + * Otherwise the body will be passed to the browser unmodified, and it + * will handle any encoding (e.g. for FormData, Blob, ArrayBuffer). + */ + body: object|null|undefined; + + /** + * Toggle whether XHR is synchronous or asynchronous. Don't change this + * to true unless You Know What You Are Doing™. + */ + sync: boolean|null|undefined; + + /** + * Specifies what data to store in the `response` property, and + * to deliver as `event.detail.response` in `response` events. + * + * One of: + * + * `text`: uses `XHR.responseText`. + * + * `xml`: uses `XHR.responseXML`. + * + * `json`: uses `XHR.responseText` parsed as JSON. + * + * `arraybuffer`: uses `XHR.response`. + * + * `blob`: uses `XHR.response`. + * + * `document`: uses `XHR.response`. + */ + handleAs: string|null|undefined; + + /** + * Set the withCredentials flag on the request. + */ + withCredentials: boolean|null|undefined; + + /** + * Set the timeout flag on the request. + */ + timeout: number|null|undefined; + + /** + * If true, automatically performs an Ajax request when either `url` or + * `params` changes. + */ + auto: boolean|null|undefined; + + /** + * If true, error messages will automatically be logged to the console. + */ + verbose: boolean|null|undefined; + + /** + * The most recent request made by this iron-ajax element. + */ + readonly lastRequest: object|null|undefined; + + /** + * The `progress` property of this element's `lastRequest`. + */ + readonly lastProgress: object|null|undefined; + + /** + * True while lastRequest is in flight. + */ + readonly loading: boolean|null|undefined; + + /** + * lastRequest's response. + * + * Note that lastResponse and lastError are set when lastRequest finishes, + * so if loading is true, then lastResponse and lastError will correspond + * to the result of the previous request. + * + * The type of the response is determined by the value of `handleAs` at + * the time that the request was generated. + */ + readonly lastResponse: object|null; + + /** + * lastRequest's error, if any. + */ + readonly lastError: object|null; + + /** + * An Array of all in-flight requests originating from this iron-ajax + * element. + */ + readonly activeRequests: any[]|null|undefined; + + /** + * Length of time in milliseconds to debounce multiple automatically generated requests. + */ + debounceDuration: number|null|undefined; + + /** + * Prefix to be stripped from a JSON response before parsing it. + * + * In order to prevent an attack using CSRF with Array responses + * (http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/) + * many backends will mitigate this by prefixing all JSON response bodies + * with a string that would be nonsensical to a JavaScript parser. + */ + jsonPrefix: string|null|undefined; + + /** + * By default, iron-ajax's events do not bubble. Setting this attribute will cause its + * request and response events as well as its iron-ajax-request, -response, and -error + * events to bubble to the window object. The vanilla error event never bubbles when + * using shadow dom even if this.bubbles is true because a scoped flag is not passed with + * it (first link) and because the shadow dom spec did not used to allow certain events, + * including events named error, to leak outside of shadow trees (second link). + * https://www.w3.org/TR/shadow-dom/#scoped-flag + * https://www.w3.org/TR/2015/WD-shadow-dom-20151215/#events-that-are-not-leaked-into-ancestor-trees + */ + bubbles: boolean|null|undefined; + + /** + * Changes the [`completes`](iron-request#property-completes) promise chain + * from `generateRequest` to reject with an object + * containing the original request, as well an error message. + * If false (default), the promise rejects with an error message only. + */ + rejectWithRequest: boolean|null|undefined; + _boundHandleResponse: Function|null|undefined; + hostAttributes: object|null; + + /** + * The query string that should be appended to the `url`, serialized from + * the current value of `params`. + */ + readonly queryString: string; + + /** + * The `url` with query string (if `params` are specified), suitable for + * providing to an `iron-request` instance. + */ + readonly requestUrl: string; + + /** + * An object that maps header names to header values, first applying the + * the value of `Content-Type` and then overlaying the headers specified + * in the `headers` property. + */ + readonly requestHeaders: object|null; + created(): void; + _onProgressChanged(event: any): void; + + /** + * Request options suitable for generating an `iron-request` instance based + * on the current state of the `iron-ajax` instance's properties. + */ + toRequestOptions(): {url: string, method?: string, async?: boolean, body?: ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string|object|null, headers?: object|null, handleAs?: string, jsonPrefix?: string, withCredentials?: boolean}; + + /** + * Performs an AJAX request to the specified URL. + */ + generateRequest(): IronRequestElement; + _handleResponse(request: any): void; + _handleError(request: any, error: any): void; + _discardRequest(request: any): void; + _requestOptionsChanged(): void; +} + +interface HTMLElementTagNameMap { + "iron-ajax": IronAjaxElement; +} diff --git a/lib/iron-ajax/iron-ajax.html b/lib/iron-ajax/iron-ajax.html index 1a9dddf6..257552e6 100644 --- a/lib/iron-ajax/iron-ajax.html +++ b/lib/iron-ajax/iron-ajax.html @@ -53,6 +53,11 @@ * Fired when a request is sent. * * @event request + */ + + /** + * Fired when a request is sent. + * * @event iron-ajax-request */ @@ -60,6 +65,11 @@ * Fired when a response is received. * * @event response + */ + + /** + * Fired when a response is received. + * * @event iron-ajax-response */ @@ -67,6 +77,11 @@ * Fired when an error is received. * * @event error + */ + + /** + * Fired when an error is received. + * * @event iron-ajax-error */ @@ -228,6 +243,8 @@ /** * The most recent request made by this iron-ajax element. + * + * @type {Object|undefined} */ lastRequest: { type: Object, @@ -235,6 +252,17 @@ readOnly: true }, + /** + * The `progress` property of this element's `lastRequest`. + * + * @type {Object|undefined} + */ + lastProgress: { + type: Object, + notify: true, + readOnly: true + }, + /** * True while lastRequest is in flight. */ @@ -348,6 +376,10 @@ 'body, sync, handleAs, jsonPrefix, withCredentials, timeout, auto)' ], + created: function() { + this._boundOnProgressChanged = this._onProgressChanged.bind(this); + }, + /** * The query string that should be appended to the `url`, serialized from * the current value of `params`. @@ -422,6 +454,10 @@ return headers; }, + _onProgressChanged: function(event) { + this._setLastProgress(event.detail.value); + }, + /** * Request options suitable for generating an `iron-request` instance based * on the current state of the `iron-ajax` instance's properties. @@ -481,8 +517,16 @@ return request; } - request.send(requestOptions); + if (this.lastRequest) { + this.lastRequest.removeEventListener('iron-request-progress-changed', + this._boundOnProgressChanged); + } + request.addEventListener('iron-request-progress-changed', + this._boundOnProgressChanged); + + request.send(requestOptions); + this._setLastProgress(null); this._setLastRequest(request); this._setLoading(true); diff --git a/lib/iron-ajax/iron-request.d.ts b/lib/iron-ajax/iron-request.d.ts new file mode 100644 index 00000000..d44d1b23 --- /dev/null +++ b/lib/iron-ajax/iron-request.d.ts @@ -0,0 +1,152 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-request.html + */ + +/// + +/** + * iron-request can be used to perform XMLHttpRequests. + * + * + * ... + * this.$.xhr.send({url: url, body: params}); + */ +interface IronRequestElement extends Polymer.Element { + + /** + * A reference to the XMLHttpRequest instance used to generate the + * network request. + */ + readonly xhr: XMLHttpRequest|null; + + /** + * A reference to the parsed response body, if the `xhr` has completely + * resolved. + */ + readonly response: any; + + /** + * A reference to the status code, if the `xhr` has completely resolved. + */ + readonly status: number|null|undefined; + + /** + * A reference to the status text, if the `xhr` has completely resolved. + */ + readonly statusText: string|null|undefined; + + /** + * A promise that resolves when the `xhr` response comes back, or rejects + * if there is an error before the `xhr` completes. + * The resolve callback is called with the original request as an argument. + * By default, the reject callback is called with an `Error` as an argument. + * If `rejectWithRequest` is true, the reject callback is called with an + * object with two keys: `request`, the original request, and `error`, the + * error object. + */ + readonly completes: Promise|null; + + /** + * An object that contains progress information emitted by the XHR if + * available. + */ + readonly progress: object|null|undefined; + + /** + * Aborted will be true if an abort of the request is attempted. + */ + readonly aborted: boolean|null|undefined; + + /** + * Errored will be true if the browser fired an error event from the + * XHR object (mainly network errors). + */ + readonly errored: boolean|null|undefined; + + /** + * TimedOut will be true if the XHR threw a timeout event. + */ + readonly timedOut: boolean|null|undefined; + hostAttributes: object|null; + + /** + * Succeeded is true if the request succeeded. The request succeeded if it + * loaded without error, wasn't aborted, and the status code is ≥ 200, and + * < 300, or if the status code is 0. + * + * The status code 0 is accepted as a success because some schemes - e.g. + * file:// - don't provide status codes. + */ + readonly succeeded: boolean; + + /** + * Sends an HTTP request to the server and returns a promise (see the `completes` + * property for details). + * + * The handling of the `body` parameter will vary based on the Content-Type + * header. See the docs for iron-ajax's `body` property for details. + * + * @param options - url The url to which the request is sent. + * - method The HTTP method to use, default is GET. + * - async By default, all requests are sent asynchronously. To send synchronous requests, + * set to false. + * - body The content for the request body for POST method. + * - headers HTTP request headers. + * - handleAs The response type. Default is 'text'. + * - withCredentials Whether or not to send credentials on the request. Default is false. + * - timeout - Timeout for request, in milliseconds. + * - rejectWithRequest Set to true to include the request object with promise rejections. + */ + send(options: {url: string, method?: string, async?: boolean, body?: ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string|object|null, headers?: object|null, handleAs?: string, jsonPrefix?: string, withCredentials?: boolean, timeout?: Number|null, rejectWithRequest?: boolean}): Promise|null; + + /** + * Attempts to parse the response body of the XHR. If parsing succeeds, + * the value returned will be deserialized based on the `responseType` + * set on the XHR. + * + * @returns The parsed response, + * or undefined if there was an empty response or parsing failed. + */ + parseResponse(): any; + + /** + * Aborts the request. + */ + abort(): void; + + /** + * @param body The given body of the request to try and encode. + * @param contentType The given content type, to infer an encoding + * from. + * @returns Either the encoded body as a string, if successful, + * or the unaltered body object if no encoding could be inferred. + */ + _encodeBodyObject(body: any, contentType: string|null): any; + + /** + * @param object The object to encode as x-www-form-urlencoded. + * @returns . + */ + _wwwFormUrlEncode(object: object|null): string; + + /** + * @param str A key or value to encode as x-www-form-urlencoded. + * @returns . + */ + _wwwFormUrlEncodePiece(str: any): string; + + /** + * Updates the status code and status text. + */ + _updateStatus(): void; +} + +interface HTMLElementTagNameMap { + "iron-request": IronRequestElement; +} diff --git a/lib/iron-ajax/iron-request.html b/lib/iron-ajax/iron-request.html index da976848..d35f7d7c 100644 --- a/lib/iron-ajax/iron-request.html +++ b/lib/iron-ajax/iron-request.html @@ -215,7 +215,10 @@ loaded: progress.loaded, total: progress.total }); - }.bind(this)); + + // Webcomponents v1 spec does not fire *-changed events when not connected + this.fire('iron-request-progress-changed', { value: this.progress }); + }.bind(this)) xhr.addEventListener('error', function(error) { this._setErrored(true); @@ -364,6 +367,7 @@ try { return JSON.parse(xhr.responseText); } catch (_) { + console.warn('Failed to parse JSON sent from ' + xhr.responseURL); return null; } } @@ -385,6 +389,7 @@ try { return JSON.parse(xhr.responseText.substring(prefixLen)); } catch (_) { + console.warn('Failed to parse JSON sent from ' + xhr.responseURL); return null; } } diff --git a/lib/iron-ajax/package-lock.json b/lib/iron-ajax/package-lock.json new file mode 100644 index 00000000..d2f43752 --- /dev/null +++ b/lib/iron-ajax/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "@polymer/iron-ajax", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-ajax/package.json b/lib/iron-ajax/package.json new file mode 100644 index 00000000..2641100a --- /dev/null +++ b/lib/iron-ajax/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-ajax", + "private": true, + "description": "Makes it easy to make ajax calls and parse the response", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-ajax.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-ajax/test/iron-ajax.html b/lib/iron-ajax/test/iron-ajax.html index eae01718..57746e1f 100644 --- a/lib/iron-ajax/test/iron-ajax.html +++ b/lib/iron-ajax/test/iron-ajax.html @@ -961,6 +961,55 @@ ajax.generateRequest(); }); }); + + suite('Progress Tests', function() { + var ajax; + + setup(function() { + server.restore(); + }); + + test('lastProgress is same as lastRequest', function(done) { + ajax = fixture('TrivialGet'); + + var lastProgressUpdated = false; + + expect(ajax.lastProgress).to.be.eql(undefined); + + ajax.generateRequest(); + + expect(ajax.lastProgress).to.be.eql(null); + + var onLastProgressChanged = function() { + expect(ajax.lastProgress.total).to.not.be.undefined; + expect(ajax.lastProgress).to.be.equal(ajax.lastRequest.progress); + lastProgressUpdated = true; + }; + + ajax.lastRequest.completes.then(function() { + // should have something from last request + expect(ajax.lastProgress).to.be.ok; + ajax.removeEventListener('last-progress-changed', + onLastProgressChanged); + ajax.generateRequest(); + + // should reset + expect(ajax.lastProgress).to.be.eql(null); + + if (lastProgressUpdated) { + done(); + } else { + done('lastProgress was never updated'); + } + }).catch(function(err) { + done(err); + }); + + server.respond(); + + ajax.addEventListener('last-progress-changed', onLastProgressChanged); + }); + }); }); diff --git a/lib/iron-ajax/test/iron-request.html b/lib/iron-ajax/test/iron-request.html index b07e033d..4530fd47 100644 --- a/lib/iron-ajax/test/iron-request.html +++ b/lib/iron-ajax/test/iron-request.html @@ -26,9 +26,13 @@ diff --git a/lib/iron-checked-element-behavior/.bower.json b/lib/iron-checked-element-behavior/.bower.json index 03ce7542..ee8030dc 100644 --- a/lib/iron-checked-element-behavior/.bower.json +++ b/lib/iron-checked-element-behavior/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-checked-element-behavior", - "version": "2.0.0", + "version": "2.1.0", "description": "Implements an element that has a checked attribute and can be added to a form", "authors": "The Polymer Authors", "keywords": [ @@ -52,11 +52,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "2.0.0", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "5d5a93884627057bab6cbf635072036376a4b572" + "tag": "v2.1.0", + "commit": "3bd74f1dda95020aad873467ca25c37dc09d6ee4" }, "_source": "https://github.com/PolymerElements/iron-checked-element-behavior.git", "_target": "^2.0.0", diff --git a/lib/iron-checked-element-behavior/.github/CODEOWNERS b/lib/iron-checked-element-behavior/.github/CODEOWNERS new file mode 100644 index 00000000..0d8c0ad6 --- /dev/null +++ b/lib/iron-checked-element-behavior/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @bicknellr +/.travis.yml @azakus diff --git a/lib/iron-checked-element-behavior/.gitignore b/lib/iron-checked-element-behavior/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-checked-element-behavior/.gitignore +++ b/lib/iron-checked-element-behavior/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-checked-element-behavior/.travis.yml b/lib/iron-checked-element-behavior/.travis.yml index f6c40972..8e714439 100644 --- a/lib/iron-checked-element-behavior/.travis.yml +++ b/lib/iron-checked-element-behavior/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- diff --git a/lib/iron-checked-element-behavior/iron-checked-element-behavior.d.ts b/lib/iron-checked-element-behavior/iron-checked-element-behavior.d.ts new file mode 100644 index 00000000..8a5882c1 --- /dev/null +++ b/lib/iron-checked-element-behavior/iron-checked-element-behavior.d.ts @@ -0,0 +1,67 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-checked-element-behavior.html + */ + +/// +/// +/// + +declare namespace Polymer { + + /** + * Use `Polymer.IronCheckedElementBehavior` to implement a custom element + * that has a `checked` property, which can be used for validation if the + * element is also `required`. Element instances implementing this behavior + * will also be registered for use in an `iron-form` element. + */ + interface IronCheckedElementBehavior extends Polymer.IronFormElementBehavior, Polymer.IronValidatableBehavior { + + /** + * Overriden from Polymer.IronFormElementBehavior + */ + value: string|null|undefined; + + /** + * Gets or sets the state, `true` is checked and `false` is unchecked. + */ + checked: boolean|null|undefined; + + /** + * If true, the button toggles the active state with each tap or press + * of the spacebar. + */ + toggles: boolean|null|undefined; + + /** + * Returns false if the element is required and not checked, and true otherwise. + * + * @param _value Ignored. + * @returns true if `required` is false or if `checked` is true. + */ + _getValidity(_value?: any): boolean; + created(): void; + + /** + * Update the aria-required label when `required` is changed. + */ + _requiredChanged(): void; + + /** + * Fire `iron-changed` when the checked state changes. + */ + _checkedChanged(): void; + + /** + * Reset value to 'on' if it is set to `undefined`. + */ + _valueChanged(): void; + } + + const IronCheckedElementBehavior: object; +} diff --git a/lib/iron-checked-element-behavior/package-lock.json b/lib/iron-checked-element-behavior/package-lock.json new file mode 100644 index 00000000..37d95af2 --- /dev/null +++ b/lib/iron-checked-element-behavior/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "@polymer/iron-checked-element-behavior", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-checked-element-behavior/package.json b/lib/iron-checked-element-behavior/package.json new file mode 100644 index 00000000..3ace8d10 --- /dev/null +++ b/lib/iron-checked-element-behavior/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-checked-element-behavior", + "private": true, + "description": "Implements an element that has a checked attribute and can be added to a form", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-checked-element-behavior.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-collapse/.bower.json b/lib/iron-collapse/.bower.json index 67054558..740fbb3e 100644 --- a/lib/iron-collapse/.bower.json +++ b/lib/iron-collapse/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-collapse", - "version": "2.0.0", + "version": "2.2.0", "description": "Provides a collapsable container", "authors": [ "The Polymer Authors" @@ -51,11 +51,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "2.0.0", + "_release": "2.2.0", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "b673ab042d565b7bfffb32ba799337b07627344e" + "tag": "v2.2.0", + "commit": "52b1ca32aca8ec3e482e643206a934a947abe27e" }, "_source": "https://github.com/PolymerElements/iron-collapse.git", "_target": "^2.0.0", diff --git a/lib/iron-collapse/.github/CODEOWNERS b/lib/iron-collapse/.github/CODEOWNERS new file mode 100644 index 00000000..c5097c0c --- /dev/null +++ b/lib/iron-collapse/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @valdrinkoshi +/.travis.yml @azakus diff --git a/lib/iron-collapse/.gitignore b/lib/iron-collapse/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-collapse/.gitignore +++ b/lib/iron-collapse/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-collapse/.travis.yml b/lib/iron-collapse/.travis.yml index 2ddebf92..e53221c7 100644 --- a/lib/iron-collapse/.travis.yml +++ b/lib/iron-collapse/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) env: global: - secure: >- diff --git a/lib/iron-collapse/README.md b/lib/iron-collapse/README.md index 549f317e..4157dac7 100644 --- a/lib/iron-collapse/README.md +++ b/lib/iron-collapse/README.md @@ -6,10 +6,13 @@ _[Demo and API docs](https://elements.polymer-project.org/elements/iron-collapse ## <iron-collapse> `iron-collapse` creates a collapsible block of content. By default, the content -will be collapsed. Use `opened` or `toggle()` to show/hide the content. +will be collapsed. Use `opened` or `toggle()` to show/hide the content. The +aria-expanded attribute should only be set on the button that controls the +collapsable area, not on the area itself. See +https://www.w3.org/WAI/GL/wiki/Using_aria-expanded_to_indicate_the_state_of_a_collapsible_element#Description ```html - +
Content goes here...
@@ -19,6 +22,7 @@ will be collapsed. Use `opened` or `toggle()` to show/hide the content. toggle: function() { this.$.collapse.toggle(); + this.$.button.setAttribute('aria-expanded', this.$.collapse.opened); } ``` diff --git a/lib/iron-collapse/bower.json b/lib/iron-collapse/bower.json index 91a0b3f9..ca0d574e 100644 --- a/lib/iron-collapse/bower.json +++ b/lib/iron-collapse/bower.json @@ -1,6 +1,6 @@ { "name": "iron-collapse", - "version": "2.0.0", + "version": "2.1.0", "description": "Provides a collapsable container", "authors": [ "The Polymer Authors" diff --git a/lib/iron-collapse/iron-collapse.d.ts b/lib/iron-collapse/iron-collapse.d.ts new file mode 100644 index 00000000..49f66eb9 --- /dev/null +++ b/lib/iron-collapse/iron-collapse.d.ts @@ -0,0 +1,110 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-collapse.html + */ + +/// +/// + +/** + * `iron-collapse` creates a collapsible block of content. By default, the content + * will be collapsed. Use `opened` or `toggle()` to show/hide the content. + * + * + * + * + *
Content goes here...
+ *
+ * + * ... + * + * toggle: function() { + * this.$.collapse.toggle(); + * } + * + * `iron-collapse` adjusts the max-height/max-width of the collapsible element to show/hide + * the content. So avoid putting padding/margin/border on the collapsible directly, + * and instead put a div inside and style that. + * + * + * + * + *
+ *
Content goes here...
+ *
+ *
+ * + * ### Styling + * + * The following custom properties and mixins are available for styling: + * + * Custom property | Description | Default + * ----------------|-------------|---------- + * `--iron-collapse-transition-duration` | Animation transition duration | `300ms` + */ +interface IronCollapseElement extends Polymer.Element, Polymer.IronResizableBehavior { + + /** + * If true, the orientation is horizontal; otherwise is vertical. + */ + horizontal: boolean|null|undefined; + + /** + * Set opened to true to show the collapse element and to false to hide it. + */ + opened: boolean|null|undefined; + + /** + * When true, the element is transitioning its opened state. When false, + * the element has finished opening/closing. + */ + readonly transitioning: boolean|null|undefined; + + /** + * Set noAnimation to true to disable animations. + */ + noAnimation: boolean|null|undefined; + hostAttributes: object|null; + readonly dimension: any; + + /** + * Toggle the opened state. + */ + toggle(): void; + show(): void; + hide(): void; + + /** + * Updates the size of the element. + * + * @param size The new value for `maxWidth`/`maxHeight` as css property value, usually `auto` or `0px`. + * @param animated if `true` updates the size with an animation, otherwise without. + */ + updateSize(size: string, animated?: boolean): void; + + /** + * enableTransition() is deprecated, but left over so it doesn't break existing code. + * Please use `noAnimation` property instead. + */ + enableTransition(enabled: any): void; + _updateTransition(enabled: any): void; + _horizontalChanged(): void; + _openedChanged(): void; + _transitionEnd(): void; + _onTransitionEnd(event: any): void; + _calcSize(): any; +} + +interface HTMLElementTagNameMap { + "iron-collapse": IronCollapseElement; +} diff --git a/lib/iron-collapse/iron-collapse.html b/lib/iron-collapse/iron-collapse.html index 9bcc8b88..32bc29eb 100644 --- a/lib/iron-collapse/iron-collapse.html +++ b/lib/iron-collapse/iron-collapse.html @@ -175,7 +175,6 @@ hostAttributes: { role: 'group', 'aria-hidden': 'true', - 'aria-expanded': 'false' }, listeners: { @@ -266,7 +265,6 @@ }, _openedChanged: function() { - this.setAttribute('aria-expanded', this.opened); this.setAttribute('aria-hidden', !this.opened); this._setTransitioning(true); diff --git a/lib/iron-collapse/package-lock.json b/lib/iron-collapse/package-lock.json new file mode 100644 index 00000000..9cf1f64c --- /dev/null +++ b/lib/iron-collapse/package-lock.json @@ -0,0 +1,974 @@ +{ + "name": "@polymer/iron-collapse", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.0", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.0", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-qtxDULQKUenuaDLW003CgC+0T0eiAfH3BrH+vSt87GLzbz5EZ6Ox6mv9rMttvhDOatbb9nYh0E1m7ydoYwUrAg==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.2", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.0.tgz", + "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.5.7" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", + "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.8.1", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.1" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.8.1.tgz", + "integrity": "sha512-MLvnM9gexFWg7nynY24eHZG6NLXocmk718sVds/sx2CAJ6iihhC0JMhhOIa6jnad9KQrHyGl/cs3mMRaaub5Fg==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.1.tgz", + "integrity": "sha1-Eahr7+rDxKo+wIYjZRo8gabQu8g=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-collapse/package.json b/lib/iron-collapse/package.json new file mode 100644 index 00000000..98037248 --- /dev/null +++ b/lib/iron-collapse/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-collapse", + "private": true, + "description": "Provides a collapsable container", + "repository": { + "type": "git", + "url": "https://github.com/PolymerElements/iron-collapse" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-collapse/test/a11y.html b/lib/iron-collapse/test/a11y.html index 6e2e835b..aa6c74b5 100644 --- a/lib/iron-collapse/test/a11y.html +++ b/lib/iron-collapse/test/a11y.html @@ -47,13 +47,15 @@ test('aria attributes', function() { assert.equal(collapse.getAttribute('role'), 'group'); - assert.equal(collapse.getAttribute('aria-expanded'), 'false'); assert.equal(collapse.getAttribute('aria-hidden'), 'true'); + // aria-expanded should only be set on the button that + // controls the collapsable area, not on the area itself. + // See https://www.w3.org/WAI/GL/wiki/Using_aria-expanded_to_indicate_the_state_of_a_collapsible_element#Description + assert.isFalse(collapse.hasAttribute('aria-expanded')); }); test('set opened to true', function() { collapse.opened = true; - assert.equal(collapse.getAttribute('aria-expanded'), 'true'); assert.equal(collapse.getAttribute('aria-hidden'), 'false'); }); diff --git a/lib/iron-demo-helpers/.bower.json b/lib/iron-demo-helpers/.bower.json index af9d1f86..91e19f70 100644 --- a/lib/iron-demo-helpers/.bower.json +++ b/lib/iron-demo-helpers/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-demo-helpers", - "version": "2.0.0", + "version": "2.1.0", "description": "Utility classes to make building demo pages easier", "authors": [ "The Polymer Authors" @@ -25,9 +25,9 @@ "dependencies": { "polymer": "Polymer/polymer#1.9 - 2", "font-roboto": "PolymerElements/font-roboto#^1", - "iron-flex-layout": "polymerelements/iron-flex-layout#1 - 2", + "iron-flex-layout": "PolymerElements/iron-flex-layout#1 - 2", "iron-location": "PolymerElements/iron-location#1 - 2", - "marked-element": "polymerelements/marked-element#1 - 2", + "marked-element": "PolymerElements/marked-element#1 - 2", "prism-element": "PolymerElements/prism-element#1 - 2" }, "devDependencies": { @@ -43,7 +43,7 @@ "font-roboto": "PolymerElements/font-roboto#^1", "iron-flex-layout": "PolymerElements/iron-flex-layout#^1.0.0", "iron-location": "PolymerElements/iron-location#^0.8.0", - "marked-element": "polymerelements/marked-element#^1.0.0", + "marked-element": "PolymerElements/marked-element#^1.0.0", "prism-element": "PolymerElements/prism-element#^1.1.0" }, "devDependencies": { @@ -60,11 +60,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "2.0.0", + "_release": "2.1.0", "_resolution": { "type": "version", - "tag": "v2.0.0", - "commit": "9afb195a0c7e31308ce3396a8ad4ed57f585ff43" + "tag": "v2.1.0", + "commit": "0136908426423d1e4a85d5c87a55234ac3848579" }, "_source": "https://github.com/PolymerElements/iron-demo-helpers.git", "_target": "^2.0.0", diff --git a/lib/iron-demo-helpers/.github/CODEOWNERS b/lib/iron-demo-helpers/.github/CODEOWNERS new file mode 100644 index 00000000..0852f5f7 --- /dev/null +++ b/lib/iron-demo-helpers/.github/CODEOWNERS @@ -0,0 +1,2 @@ +* @e111077 @notwaldorf +/.travis.yml @azakus diff --git a/lib/iron-demo-helpers/.gitignore b/lib/iron-demo-helpers/.gitignore index 2be39e49..678c29bf 100644 --- a/lib/iron-demo-helpers/.gitignore +++ b/lib/iron-demo-helpers/.gitignore @@ -1,2 +1,3 @@ bower_components* bower-*.json +node_modules diff --git a/lib/iron-demo-helpers/.travis.yml b/lib/iron-demo-helpers/.travis.yml index a249d59c..660d8cde 100644 --- a/lib/iron-demo-helpers/.travis.yml +++ b/lib/iron-demo-helpers/.travis.yml @@ -3,6 +3,10 @@ sudo: required before_script: - npm install -g polymer-cli - polymer install --variants + - >- + npm run update-types && git diff --exit-code || (echo -e + '\n\033[31mERROR:\033[0m Typings are stale. Please run "npm run + update-types".' && false) node_js: stable addons: firefox: latest diff --git a/lib/iron-demo-helpers/bower.json b/lib/iron-demo-helpers/bower.json index 3932f005..fc3aa14d 100644 --- a/lib/iron-demo-helpers/bower.json +++ b/lib/iron-demo-helpers/bower.json @@ -1,6 +1,6 @@ { "name": "iron-demo-helpers", - "version": "2.0.0", + "version": "2.1.0", "description": "Utility classes to make building demo pages easier", "authors": [ "The Polymer Authors" @@ -25,9 +25,9 @@ "dependencies": { "polymer": "Polymer/polymer#1.9 - 2", "font-roboto": "PolymerElements/font-roboto#^1", - "iron-flex-layout": "polymerelements/iron-flex-layout#1 - 2", + "iron-flex-layout": "PolymerElements/iron-flex-layout#1 - 2", "iron-location": "PolymerElements/iron-location#1 - 2", - "marked-element": "polymerelements/marked-element#1 - 2", + "marked-element": "PolymerElements/marked-element#1 - 2", "prism-element": "PolymerElements/prism-element#1 - 2" }, "devDependencies": { @@ -43,7 +43,7 @@ "font-roboto": "PolymerElements/font-roboto#^1", "iron-flex-layout": "PolymerElements/iron-flex-layout#^1.0.0", "iron-location": "PolymerElements/iron-location#^0.8.0", - "marked-element": "polymerelements/marked-element#^1.0.0", + "marked-element": "PolymerElements/marked-element#^1.0.0", "prism-element": "PolymerElements/prism-element#^1.1.0" }, "devDependencies": { diff --git a/lib/iron-demo-helpers/demo-pages-shared-styles.d.ts b/lib/iron-demo-helpers/demo-pages-shared-styles.d.ts new file mode 100644 index 00000000..f9410b30 --- /dev/null +++ b/lib/iron-demo-helpers/demo-pages-shared-styles.d.ts @@ -0,0 +1,14 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * demo-pages-shared-styles.html + */ + +/// +/// +/// + diff --git a/lib/iron-demo-helpers/demo-snippet.d.ts b/lib/iron-demo-helpers/demo-snippet.d.ts new file mode 100644 index 00000000..596daca9 --- /dev/null +++ b/lib/iron-demo-helpers/demo-snippet.d.ts @@ -0,0 +1,59 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * demo-snippet.html + */ + +/// +/// +/// +/// + +/** + * `demo-snippet` is a helper element that displays the source of a code snippet and + * its rendered demo. It can be used for both native elements and + * Polymer elements. + * + * Example of a native element demo + * + * + * + * + * + * Example of a Polymer demo + * + * + * + * + * + * ### Styling + * + * The following custom properties and mixins are available for styling: + * + * Custom property | Description | Default + * ----------------|-------------|---------- + * `--demo-snippet` | Mixin applied to the entire element | `{}` + * `--demo-snippet-demo` | Mixin applied to just the demo section | `{}` + * `--demo-snippet-code` | Mixin applied to just the code section | `{}` + */ +interface DemoSnippetElement extends Polymer.Element { + _markdown: string|null|undefined; + attached(): void; + detached(): void; + _updateMarkdown(): void; + _copyToClipboard(): any; + _resetCopyButtonState(): void; +} + +interface HTMLElementTagNameMap { + "demo-snippet": DemoSnippetElement; +} diff --git a/lib/iron-demo-helpers/demo-snippet.html b/lib/iron-demo-helpers/demo-snippet.html index 7accbff6..5767a2f3 100644 --- a/lib/iron-demo-helpers/demo-snippet.html +++ b/lib/iron-demo-helpers/demo-snippet.html @@ -87,7 +87,7 @@ background-color: var(--google-grey-100); font-size: 13px; overflow: auto; - @apply(--demo-snippet-code); + @apply --demo-snippet-code; } .code > pre { margin: 0; diff --git a/lib/iron-demo-helpers/package-lock.json b/lib/iron-demo-helpers/package-lock.json new file mode 100644 index 00000000..c3eced9f --- /dev/null +++ b/lib/iron-demo-helpers/package-lock.json @@ -0,0 +1,983 @@ +{ + "name": "@polymer/iron-demo-helpers", + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@polymer/gen-typescript-declarations": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@polymer/gen-typescript-declarations/-/gen-typescript-declarations-1.2.0.tgz", + "integrity": "sha512-a5DFXI3TdZSVOMH4608LVaBLmcr+mwM2+B8OSBiB9WFNCtdqzUXwtB5We6vBzrThXlO4uRo7d2pEqjNXMAlEkA==", + "dev": true, + "requires": { + "@types/doctrine": "0.0.3", + "@types/fs-extra": "5.0.1", + "@types/glob": "5.0.35", + "command-line-args": "5.0.2", + "command-line-usage": "4.1.0", + "doctrine": "2.1.0", + "escodegen": "1.9.1", + "fs-extra": "5.0.0", + "glob": "7.1.2", + "minimatch": "3.0.4", + "polymer-analyzer": "3.0.0-pre.12" + } + }, + "@types/babel-generator": { + "version": "6.25.1", + "resolved": "https://registry.npmjs.org/@types/babel-generator/-/babel-generator-6.25.1.tgz", + "integrity": "sha512-nKNz9Ch4WP2TFZjQROhxqqS2SCk0OoDzGazJI6S+2sGgW9P7N4o3vluZAXFuPEnRqtz2A0vrrkK3tjQktxIlRw==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-traverse": { + "version": "6.25.3", + "resolved": "https://registry.npmjs.org/@types/babel-traverse/-/babel-traverse-6.25.3.tgz", + "integrity": "sha512-4FaulWyA7nrXPkzoukL2VmSpxCnBZwc+MgwZqO30gtHCrtaUXnoxymdYfxzf3CZN80zjtrVzKfLlZ7FPYvrhQQ==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/babel-types": { + "version": "6.25.2", + "resolved": "https://registry.npmjs.org/@types/babel-types/-/babel-types-6.25.2.tgz", + "integrity": "sha512-+3bMuktcY4a70a0KZc8aPJlEOArPuAKQYHU5ErjkOqGJdx8xuEEVK6nWogqigBOJ8nKPxRpyCUDTCPmZ3bUxGA==", + "dev": true + }, + "@types/babylon": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.2.tgz", + "integrity": "sha512-+Jty46mPaWe1VAyZbfvgJM4BAdklLWxrT5tc/RjvCgLrtk6gzRY6AOnoWFv4p6hVxhJshDdr2hGVn56alBp97Q==", + "dev": true, + "requires": { + "@types/babel-types": "6.25.2" + } + }, + "@types/chai": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.2.tgz", + "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", + "dev": true + }, + "@types/chai-subset": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/chai-subset/-/chai-subset-1.3.1.tgz", + "integrity": "sha512-Aof+FLfWzBPzDgJ2uuBuPNOBHVx9Siyw4vmOcsMgsuxX1nfUWSlzpq4pdvQiaBgGjGS7vP/Oft5dpJbX4krT1A==", + "dev": true, + "requires": { + "@types/chai": "4.1.2" + } + }, + "@types/chalk": { + "version": "0.4.31", + "resolved": "https://registry.npmjs.org/@types/chalk/-/chalk-0.4.31.tgz", + "integrity": "sha1-ox10JBprHtu5c8822XooloNKUfk=", + "dev": true + }, + "@types/clone": { + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@types/clone/-/clone-0.1.30.tgz", + "integrity": "sha1-5zZWSMG0ITalnH1QQGN7O1yDthQ=", + "dev": true + }, + "@types/cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@types/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-jgvuj33suVIlDaDK6+BeMFkcF+8=", + "dev": true + }, + "@types/doctrine": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.3.tgz", + "integrity": "sha1-6JLSk8ksnB0/mvcsFaVU+8fgiVo=", + "dev": true + }, + "@types/events": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.2.0.tgz", + "integrity": "sha512-KEIlhXnIutzKwRbQkGWb/I4HFqBuUykAdHgDED6xqwXJfONCjF5VoE0cXEiurh3XauygxzeDzgtXUqvLkxFzzA==", + "dev": true + }, + "@types/fs-extra": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-5.0.1.tgz", + "integrity": "sha512-h3wnflb+jMTipvbbZnClgA2BexrT4w0GcfoCz5qyxd0IRsbqhLSyesM6mqZTAnhbVmhyTm5tuxfRu9R+8l+lGw==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/glob": { + "version": "5.0.35", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.35.tgz", + "integrity": "sha512-wc+VveszMLyMWFvXLkloixT4n0harUIVZjnpzztaZ0nKLuul7Z32iMt2fUFGAaZ4y1XWjFRMtCI5ewvyh4aIeg==", + "dev": true, + "requires": { + "@types/events": "1.2.0", + "@types/minimatch": "3.0.3", + "@types/node": "9.4.6" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "9.4.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-9.4.6.tgz", + "integrity": "sha512-CTUtLb6WqCCgp6P59QintjHWqzf4VL1uPA27bipLAPxFqrtK1gEYllePzTICGqQ8rYsCbpnsNypXjjDzGAAjEQ==", + "dev": true + }, + "@types/parse5": { + "version": "2.2.34", + "resolved": "https://registry.npmjs.org/@types/parse5/-/parse5-2.2.34.tgz", + "integrity": "sha1-44cKEOgnNacg9i1x3NGDunjvOp0=", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "@types/winston": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.3.8.tgz", + "integrity": "sha512-QqR0j08RCS1AQYPMRPHikEpcmK+2aEEbcSzWLwOqyJ4FhLmHUx/WjRrnn7tTQg/y4IKnMhzskh/o7qvGIZZ7iA==", + "dev": true, + "requires": { + "@types/node": "9.4.6" + } + }, + "ansi-escape-sequences": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-escape-sequences/-/ansi-escape-sequences-4.0.0.tgz", + "integrity": "sha512-v+0wW9Wezwsyb0uF4aBVCjmSqit3Ru7PZFziGF0o2KwTvN2zWfTi3BRLq9EkJFdg3eBbyERXGTntVpBxH1J68Q==", + "dev": true, + "requires": { + "array-back": "2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "find-replace": "2.0.1" + } + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "dev": true, + "requires": { + "typical": "2.6.1" + } + }, + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "detect-indent": "4.0.0", + "jsesc": "1.3.0", + "lodash": "4.17.5", + "source-map": "0.5.7", + "trim-right": "1.0.1" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "6.26.0", + "babel-messages": "6.23.0", + "babel-runtime": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "debug": "2.6.9", + "globals": "9.18.0", + "invariant": "2.2.3", + "lodash": "4.17.5" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "esutils": "2.0.2", + "lodash": "4.17.5", + "to-fast-properties": "1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bower": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/bower/-/bower-1.8.2.tgz", + "integrity": "sha1-rfU1KcjUrwLvJPuNU0HBQZ0z4vc=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "dev": true + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "dev": true, + "requires": { + "argv-tools": "0.1.1", + "array-back": "2.0.0", + "find-replace": "2.0.1", + "lodash.camelcase": "4.3.0", + "typical": "2.6.1" + } + }, + "command-line-usage": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-4.1.0.tgz", + "integrity": "sha512-MxS8Ad995KpdAC0Jopo/ovGIroV/m0KHwzKfXxKag6FHOkGsH8/lv5yjgablcRxCJJC0oJeUMuO/gmaq+Wq46g==", + "dev": true, + "requires": { + "ansi-escape-sequences": "4.0.0", + "array-back": "2.0.0", + "table-layout": "0.4.2", + "typical": "2.6.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", + "dev": true + }, + "cssbeautify": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cssbeautify/-/cssbeautify-0.3.1.tgz", + "integrity": "sha1-Et0fc0A1wub6ymfcvc73TkKBE5c=", + "dev": true + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.0.tgz", + "integrity": "sha1-bvSgmwX5iw41jW2T1Mo8rsZnKAM=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "2.0.1" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "2.0.2" + } + }, + "dom5": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/dom5/-/dom5-3.0.0.tgz", + "integrity": "sha512-PbE+7C4Sh1dHDTLNuSDaMUGD1ivDiSZw0L+a9xVUzUKeQ8w3vdzfKHRA07CxcrFZZOa1SGl2nIJ9T49j63q+bg==", + "dev": true, + "requires": { + "@types/parse5": "2.2.34", + "clone": "2.1.1", + "parse5": "4.0.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.9.1.tgz", + "integrity": "sha512-6hTjO1NAWkHnDk3OqQ4YrCuwwmGHL9S3nPlzBOUG/R44rda3wLNrfvQ5fkSGjyhHFKM7ALPKcKGrwvCLe0lC7Q==", + "dev": true, + "requires": { + "esprima": "3.1.3", + "estraverse": "4.2.0", + "esutils": "2.0.2", + "optionator": "0.8.2", + "source-map": "0.6.1" + } + }, + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "test-value": "3.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "dev": true, + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "indent": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/indent/-/indent-0.0.2.tgz", + "integrity": "sha1-jHnwgBkFWbaHA0uEx676l9WpEdk=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "invariant": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.3.tgz", + "integrity": "sha512-7Z5PPegwDTyjbaeCnV0efcyS6vdKAU51kpEmS7QFib3P4822l8ICYyMn7qvJnc+WzLoDsuI9gPMKbJ8pCu8XtA==", + "dev": true, + "requires": { + "loose-envify": "1.3.1" + } + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "1.0.1" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "4.1.11" + } + }, + "jsonschema": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.2.tgz", + "integrity": "sha512-iX5OFQ6yx9NgbHCwse51ohhKgLuLL7Z5cNOeZOPIlDUtAMrxlruHLzVZxbltdHE5mEDXN+75oFOwq6Gn0MZwsA==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2", + "type-check": "0.3.2" + } + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "lodash.padend": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.padend/-/lodash.padend-4.6.1.tgz", + "integrity": "sha1-U8y6BH0G4VjTEfRdpiX05J5vFm4=", + "dev": true + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimatch-all": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/minimatch-all/-/minimatch-all-1.1.0.tgz", + "integrity": "sha1-QMSWonouEo0Zv3WOdrsBoMcUV4c=", + "dev": true, + "requires": { + "minimatch": "3.0.4" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "0.1.3", + "fast-levenshtein": "2.0.6", + "levn": "0.3.0", + "prelude-ls": "1.1.2", + "type-check": "0.3.2", + "wordwrap": "1.0.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "plylog": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/plylog/-/plylog-0.5.0.tgz", + "integrity": "sha1-yXbrodgNLdmRAF18EQ2vh0FUeI8=", + "dev": true, + "requires": { + "@types/node": "4.2.23", + "@types/winston": "2.3.8", + "winston": "2.4.0" + }, + "dependencies": { + "@types/node": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-4.2.23.tgz", + "integrity": "sha512-U6IchCNLRyswc9p6G6lxWlbE+KwAhZp6mGo6MD2yWpmFomhYmetK+c98OpKyvphNn04CU3aXeJrXdOqbXVTS/w==", + "dev": true + } + } + }, + "polymer-analyzer": { + "version": "3.0.0-pre.12", + "resolved": "https://registry.npmjs.org/polymer-analyzer/-/polymer-analyzer-3.0.0-pre.12.tgz", + "integrity": "sha512-QQL70IC85hI6q9uQeresEMcT1Qf8YR/zDe1qG8WWeeFAZk8z0lmzUpsfcAWz+bM4wpDdXrtd4HitIs4p0CHl/w==", + "dev": true, + "requires": { + "@types/babel-generator": "6.25.1", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "6.25.2", + "@types/babylon": "6.16.2", + "@types/chai-subset": "1.3.1", + "@types/chalk": "0.4.31", + "@types/clone": "0.1.30", + "@types/cssbeautify": "0.3.1", + "@types/doctrine": "0.0.1", + "@types/minimatch": "3.0.3", + "@types/node": "6.0.101", + "@types/parse5": "2.2.34", + "babel-generator": "6.26.1", + "babel-traverse": "6.26.0", + "babel-types": "6.26.0", + "babylon": "6.18.0", + "chalk": "1.1.3", + "clone": "2.1.1", + "cssbeautify": "0.3.1", + "doctrine": "2.1.0", + "dom5": "3.0.0", + "indent": "0.0.2", + "jsonschema": "1.2.2", + "minimatch": "3.0.4", + "parse5": "4.0.0", + "polymer-project-config": "3.9.0", + "shady-css-parser": "0.1.0", + "stable": "0.1.6", + "strip-indent": "2.0.0", + "vscode-uri": "1.0.3" + }, + "dependencies": { + "@types/doctrine": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@types/doctrine/-/doctrine-0.0.1.tgz", + "integrity": "sha1-uZny2fe0PKvgoaLzm8IDvH3K2p0=", + "dev": true + }, + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "polymer-project-config": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/polymer-project-config/-/polymer-project-config-3.9.0.tgz", + "integrity": "sha512-WPOqlV2W/M4Ni40QIqYSv8PE7H4rjiPm1KEf02QPtjZOGlAC4Rv7e6UJ1Ke1O70WT5bydcsEn3LViFIqYpVOJw==", + "dev": true, + "requires": { + "@types/node": "6.0.101", + "jsonschema": "1.2.2", + "minimatch-all": "1.1.0", + "plylog": "0.5.0" + }, + "dependencies": { + "@types/node": { + "version": "6.0.101", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.101.tgz", + "integrity": "sha512-IQ7V3D6+kK1DArTqTBrnl3M+YgJZLw8ta8w3Q9xjR79HaJzMAoTbZ8TNzUTztrkCKPTqIstE2exdbs1FzsYLUw==", + "dev": true + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "reduce-flatten": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-1.0.1.tgz", + "integrity": "sha1-JYx479FT3fk8tWEjf2EYTzaW4yc=", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "1.0.2" + } + }, + "shady-css-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/shady-css-parser/-/shady-css-parser-0.1.0.tgz", + "integrity": "sha512-irfJUUkEuDlNHKZNAp2r7zOyMlmbfVJ+kWSfjlCYYUx/7dJnANLCyTzQZsuxy5NJkvtNwSxY5Gj8MOlqXUQPyA==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + }, + "stable": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", + "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=", + "dev": true + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "2.1.1" + } + }, + "strip-indent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-2.0.0.tgz", + "integrity": "sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=", + "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "table-layout": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-0.4.2.tgz", + "integrity": "sha512-tygyl5+eSHj4chpq5Zfy6cpc7MOUBClAW9ozghFH7hg9bAUzShOYn+/vUzTRkKOSLJWKfgYtP2tAU2c0oAD8eg==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "deep-extend": "0.5.0", + "lodash.padend": "4.6.1", + "typical": "2.6.1", + "wordwrapjs": "3.0.0" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "dev": true, + "requires": { + "array-back": "2.0.0", + "typical": "2.6.1" + } + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "1.1.2" + } + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=", + "dev": true + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=", + "dev": true + }, + "vscode-uri": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.3.tgz", + "integrity": "sha1-Yxvb9xbcyrDmUpGo3CXCMjIIWlI=", + "dev": true + }, + "winston": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.4.0.tgz", + "integrity": "sha1-gIBQuT1SZh7Z+2wms/DIJnCLCu4=", + "dev": true, + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "stack-trace": "0.0.10" + } + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "wordwrapjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-3.0.0.tgz", + "integrity": "sha512-mO8XtqyPvykVCsrwj5MlOVWvSnCdT+C+QVbm6blradR7JExAhbkZ7hZ9A+9NUtwzSqrlUo9a67ws0EiILrvRpw==", + "dev": true, + "requires": { + "reduce-flatten": "1.0.1", + "typical": "2.6.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + } + } +} diff --git a/lib/iron-demo-helpers/package.json b/lib/iron-demo-helpers/package.json new file mode 100644 index 00000000..9f5a39c7 --- /dev/null +++ b/lib/iron-demo-helpers/package.json @@ -0,0 +1,17 @@ +{ + "name": "@polymer/iron-demo-helpers", + "private": true, + "description": "Utility classes to make building demo pages easier", + "repository": { + "type": "git", + "url": "git://github.com/PolymerElements/iron-demo-helpers.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "@polymer/gen-typescript-declarations": "^1.2.0", + "bower": "^1.8.0" + }, + "scripts": { + "update-types": "bower install && gen-typescript-declarations --deleteExisting --outDir ." + } +} diff --git a/lib/iron-demo-helpers/url-bar.d.ts b/lib/iron-demo-helpers/url-bar.d.ts new file mode 100644 index 00000000..e0d089df --- /dev/null +++ b/lib/iron-demo-helpers/url-bar.d.ts @@ -0,0 +1,40 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * url-bar.html + */ + +/// +/// +/// + +/** + * `url-bar` is a helper element that displays a simple read-only URL bar if + * and only if the page is in an iframe. In this way we can demo elements that + * deal with the URL in our iframe-based demo environments. + * + * If the page is not in an iframe, the url-bar element is not displayed. + * + * ### Styling + * + * The following custom properties and mixins are available for styling: + * + * Custom property | Description | Default + * ----------------|-------------|---------- + * `--url-bar` | Mixin applied to the entire element | `{}` + */ +interface UrlBarElement extends Polymer.Element { + readonly url: string|null|undefined; + inIframe: boolean|null|undefined; + path: string|null|undefined; + query: string|null|undefined; + hash: string|null|undefined; +} + +interface HTMLElementTagNameMap { + "url-bar": UrlBarElement; +} diff --git a/lib/iron-doc-viewer/.bower.json b/lib/iron-doc-viewer/.bower.json index 40055690..e479bb4f 100644 --- a/lib/iron-doc-viewer/.bower.json +++ b/lib/iron-doc-viewer/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-doc-viewer", - "version": "3.0.4", + "version": "3.2.0", "authors": [ "The Polymer Authors" ], @@ -56,11 +56,11 @@ "resolutions": { "webcomponentsjs": "^1.0.0" }, - "_release": "3.0.4", + "_release": "3.2.0", "_resolution": { "type": "version", - "tag": "v3.0.4", - "commit": "17a2a1a8712bd3fb5d46089fd734964241deee22" + "tag": "v3.2.0", + "commit": "f39c6c6bdd82d4558731e435e1ea565b3bcfc140" }, "_source": "https://github.com/PolymerElements/iron-doc-viewer.git", "_target": "^3.0.4", diff --git a/lib/iron-doc-viewer/bower.json b/lib/iron-doc-viewer/bower.json index fcc29680..de807baf 100644 --- a/lib/iron-doc-viewer/bower.json +++ b/lib/iron-doc-viewer/bower.json @@ -1,6 +1,6 @@ { "name": "iron-doc-viewer", - "version": "3.0.0", + "version": "3.1.0", "authors": [ "The Polymer Authors" ], diff --git a/lib/iron-doc-viewer/default-theme.d.ts b/lib/iron-doc-viewer/default-theme.d.ts new file mode 100644 index 00000000..34f22377 --- /dev/null +++ b/lib/iron-doc-viewer/default-theme.d.ts @@ -0,0 +1,13 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * default-theme.html + */ + +/// +/// + diff --git a/lib/iron-doc-viewer/iron-doc-api.d.ts b/lib/iron-doc-viewer/iron-doc-api.d.ts new file mode 100644 index 00000000..c2cf5cca --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-api.d.ts @@ -0,0 +1,35 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-api.html + */ + +/// +/// +/// +/// +/// +/// + +interface IronDocApiElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + descriptor: object|null|undefined; + _showProtectedProperties: boolean|null|undefined; + _showProtectedMethods: boolean|null|undefined; + _showProtectedEvents: boolean|null|undefined; + readonly _staticMethods: any; + readonly _hasMethods: any; + _anyVisible(items: any): any; + _public(items: any): any; + _protected(items: any): any; + _protectedCount(): any; + _computeStaticMethods(descriptor: any): any; + _computeHasMethods(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-api": IronDocApiElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-api.html b/lib/iron-doc-viewer/iron-doc-api.html index 629012cf..d98832a0 100644 --- a/lib/iron-doc-viewer/iron-doc-api.html +++ b/lib/iron-doc-viewer/iron-doc-api.html @@ -62,8 +62,9 @@

-
+

Methods

@@ -151,13 +152,19 @@

behaviors: [Polymer.IronDocViewerBehavior], properties: { + descriptor: Object, + _showProtectedProperties: Boolean, _showProtectedMethods: Boolean, _showProtectedEvents: Boolean, _staticMethods: { computed: '_computeStaticMethods(descriptor)' - } + }, + + _hasMethods: { + computed: '_computeHasMethods(descriptor)' + }, }, _anyVisible: function(items) { @@ -203,6 +210,11 @@

_computeStaticMethods: function(descriptor) { return descriptor.staticMethods || []; }, + + _computeHasMethods: function(descriptor) { + return (descriptor.methods && descriptor.methods.length > 0) || + (descriptor.staticMethods && descriptor.staticMethods.length > 0); + }, }); })(); diff --git a/lib/iron-doc-viewer/iron-doc-behavior.d.ts b/lib/iron-doc-viewer/iron-doc-behavior.d.ts new file mode 100644 index 00000000..21bed27f --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-behavior.d.ts @@ -0,0 +1,33 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-behavior.html + */ + +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/** + * `iron-doc-behavior` renders documentation about a Polymer 1.x behavior from a + * JSON descriptor output by + * [Polymer Analyzer](https://github.com/Polymer/polymer-analyzer). + */ +interface IronDocBehaviorElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + readonly title: any; + _computeTitle(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-behavior": IronDocBehaviorElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-class.d.ts b/lib/iron-doc-viewer/iron-doc-class.d.ts new file mode 100644 index 00000000..82061baf --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-class.d.ts @@ -0,0 +1,31 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-class.html + */ + +/// +/// +/// +/// +/// +/// +/// + +/** + * `iron-doc-class` renders documentation about a JavaScript class from a JSON + * descriptor output by + * [Polymer Analyzer](https://github.com/Polymer/polymer-analyzer). + */ +interface IronDocClassElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + readonly title: any; + _computeTitle(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-class": IronDocClassElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-demo.d.ts b/lib/iron-doc-viewer/iron-doc-demo.d.ts new file mode 100644 index 00000000..3448d308 --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-demo.d.ts @@ -0,0 +1,23 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-demo.html + */ + +/// +/// + +interface IronDocDemoElement extends Polymer.Element { + demo: object|null|undefined; + srcPrefix: string|null|undefined; + readonly title: any; + _computeTitle(demo: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-demo": IronDocDemoElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-element.d.ts b/lib/iron-doc-viewer/iron-doc-element.d.ts new file mode 100644 index 00000000..08ffaebf --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-element.d.ts @@ -0,0 +1,33 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-element.html + */ + +/// +/// +/// +/// +/// +/// +/// + +/** + * `iron-doc-element` renders documentation about a custom element from a JSON + * descriptor output by + * [Polymer Analyzer](https://github.com/Polymer/polymer-analyzer). + */ +interface IronDocElementElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + readonly title: any; + _superclassUrl(superclass: any): any; + _superclassTarget(superclass: any): any; + _computeTitle(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-element": IronDocElementElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-function.d.ts b/lib/iron-doc-viewer/iron-doc-function.d.ts new file mode 100644 index 00000000..385c519d --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-function.d.ts @@ -0,0 +1,30 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-function.html + */ + +/// +/// +/// + +/** + * Renders documentation describing a function or method. + */ +interface IronDocFunctionElement extends Polymer.Element { + anchorId: string|null|undefined; + static: boolean|null|undefined; + readonly _privacy: string|null|undefined; + readonly _showParamList: boolean|null|undefined; + addImportPath: boolean|null|undefined; + _computePrivacy(descriptor: any): any; + _computeShowParamList(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-function": IronDocFunctionElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-function.html b/lib/iron-doc-viewer/iron-doc-function.html index 1fcbfdc9..1c3d3372 100644 --- a/lib/iron-doc-viewer/iron-doc-function.html +++ b/lib/iron-doc-viewer/iron-doc-function.html @@ -48,6 +48,10 @@ .privacy { color: #666; } + + .import-path { + padding-left: 25px; + } @@ -75,6 +79,8 @@ Inherited from [[descriptor.inheritedFrom]]

+
Requires import: [[descriptor.sourceRange.file]]
+ @@ -124,6 +130,11 @@ _showParamList: { type: Boolean, computed: '_computeShowParamList(descriptor)' + }, + + addImportPath: { + type: Boolean, + value: false } }, diff --git a/lib/iron-doc-viewer/iron-doc-hide-bar.d.ts b/lib/iron-doc-viewer/iron-doc-hide-bar.d.ts new file mode 100644 index 00000000..b92ede6c --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-hide-bar.d.ts @@ -0,0 +1,21 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-hide-bar.html + */ + +/// +/// + +interface IronDocHideBarElement extends Polymer.Element { + visible: boolean|null|undefined; + _toggle(ev: any): void; +} + +interface HTMLElementTagNameMap { + "iron-doc-hide-bar": IronDocHideBarElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-mixin.d.ts b/lib/iron-doc-viewer/iron-doc-mixin.d.ts new file mode 100644 index 00000000..22ae980b --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-mixin.d.ts @@ -0,0 +1,31 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-mixin.html + */ + +/// +/// +/// +/// +/// +/// +/// + +/** + * `iron-doc-element` renders documentation about a JavaScript mixin from a JSON + * descriptor output by + * [Polymer Analyzer](https://github.com/Polymer/polymer-analyzer). + */ +interface IronDocMixinElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + readonly title: any; + _computeTitle(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-mixin": IronDocMixinElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-namespace.d.ts b/lib/iron-doc-viewer/iron-doc-namespace.d.ts new file mode 100644 index 00000000..099b5e49 --- /dev/null +++ b/lib/iron-doc-viewer/iron-doc-namespace.d.ts @@ -0,0 +1,32 @@ +/** + * DO NOT EDIT + * + * This file was automatically generated by + * https://github.com/Polymer/gen-typescript-declarations + * + * To modify these typings, edit the source file(s): + * iron-doc-namespace.html + */ + +/// +/// +/// +/// +/// +/// +/// +/// + +/** + * `iron-doc-namespace` renders documentation about a JavaScript namespace from a + * JSON descriptor output by + * [Polymer Analyzer](https://github.com/Polymer/polymer-analyzer). + */ +interface IronDocNamespaceElement extends Polymer.Element, Polymer.IronDocViewerBehavior { + readonly title: any; + _computeTitle(descriptor: any): any; +} + +interface HTMLElementTagNameMap { + "iron-doc-namespace": IronDocNamespaceElement; +} diff --git a/lib/iron-doc-viewer/iron-doc-namespace.html b/lib/iron-doc-viewer/iron-doc-namespace.html index 09d317ed..16d4a775 100644 --- a/lib/iron-doc-viewer/iron-doc-namespace.html +++ b/lib/iron-doc-viewer/iron-doc-namespace.html @@ -111,6 +111,7 @@