` (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
+ *
+ *
+ *
+ *
+ * item 1
+ *
+ *
+ * item 2
+ *
+ *
+ * item 3
+ *
+ *
+ *
+ * ```
+ *
+ * ### 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,EAAA,GACAS,EAAAT,EAAA,GACAU,EAAAV,EAAA,IACAW,EAAAX,EAAA,GACAY,EAAAZ,EAAA,IACAa,EAAA,GAAAD,GAAAE,OAAA,qBAKAf,GAAAgB,cAAA,WACA,GAAAC,GAAA,CACA,mBACA,MAAA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ACN,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.