diff --git a/README.md b/README.md index 4dc327b..369da42 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ export class AppModule {} * [Description List](/src/description-list/README.md) * [Dotnav](/src/dotnav/README.md) * [Tabs](/src/tabs/README.md) +* [Table](/src/table/README.md) ### In Progress @@ -190,7 +191,6 @@ export class AppModule {} * [Subnav](/src//README.md) * [SVG](/src//README.md) * [Switcher](/src//README.md) -* [Table](/src//README.md) * [Text](/src//README.md) * [Thumbnav](/src//README.md) * [Tile](/src//README.md) diff --git a/develop/src/app/app.components.module.ts b/develop/src/app/app.components.module.ts index 232e35d..e0ec21e 100644 --- a/develop/src/app/app.components.module.ts +++ b/develop/src/app/app.components.module.ts @@ -17,6 +17,7 @@ import { LoadingComponent } from '../../../src/loading/loading.component'; import { AlertComponent } from '../../../src/alert/alert.component'; import { SpinnerComponent } from '../../../src/spinner/spinner.component'; import { TabsComponent } from '../../../src/tabs/tabs.component'; +import { TableComponent } from '../../../src/table/table.component'; import { DescriptionListComponent } from '../../../src/description-list/description-list.component'; import { RegularMarkdownComponent } from './markdown-reader/markdown-regular.component'; @@ -46,7 +47,8 @@ import { NavComponent } from './nav-view/nav-component'; DotnavComponent, LoadingComponent, SpinnerComponent, - TabsComponent + TabsComponent, + TableComponent ] }) export class AppComponentsModule {} diff --git a/develop/src/app/app.routing.module.ts b/develop/src/app/app.routing.module.ts index 487fa68..abb378f 100644 --- a/develop/src/app/app.routing.module.ts +++ b/develop/src/app/app.routing.module.ts @@ -27,6 +27,7 @@ import { DotnavViewComponent } from './dotnav-view/dotnav-view.component'; import { LoadingViewComponent } from './loading-view/loading-view.component'; import { SpinnerViewComponent } from './spinner-view/spinner-view.component'; import { TabsViewComponent } from './tabs-view/tabs-view.component'; +import { TableViewComponent } from './table-view/table-view.component'; @Module({ imports: [ @@ -124,6 +125,10 @@ import { TabsViewComponent } from './tabs-view/tabs-view.component'; path: '/ui-kit/tabs', component: TabsViewComponent }, + { + path: '/ui-kit/table', + component: TableViewComponent + }, ], { log: true, baseUrl: '/ui-kit' } ) diff --git a/develop/src/app/nav-view/nav-component.ts b/develop/src/app/nav-view/nav-component.ts index a664f5f..49a5005 100644 --- a/develop/src/app/nav-view/nav-component.ts +++ b/develop/src/app/nav-view/nav-component.ts @@ -42,6 +42,7 @@ import { Nav } from '../../../../src/nav'; Loading Spinner Tabs + Table 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the publish operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n */\nexport function refCount(): MonoTypeOperatorFunction {\n return function refCountOperatorFunction(source: ConnectableObservable): Observable {\n return source.lift(new RefCountOperator(source));\n } as MonoTypeOperatorFunction;\n}\n\nclass RefCountOperator implements Operator {\n constructor(private connectable: ConnectableObservable) {\n }\n call(subscriber: Subscriber, source: any): TeardownLogic {\n\n const { connectable } = this;\n ( connectable)._refCount++;\n\n const refCounter = new RefCountSubscriber(subscriber, connectable);\n const subscription = source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n ( refCounter).connection = connectable.connect();\n }\n\n return subscription;\n }\n}\n\nclass RefCountSubscriber extends Subscriber {\n\n private connection: Subscription;\n\n constructor(destination: Subscriber,\n private connectable: ConnectableObservable) {\n super(destination);\n }\n\n protected _unsubscribe() {\n\n const { connectable } = this;\n if (!connectable) {\n this.connection = null;\n return;\n }\n\n this.connectable = null;\n const refCount = ( connectable)._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n\n ( connectable)._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // )\n // .subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n const { connection } = this;\n const sharedConnection = ( connectable)._connection;\n this.connection = null;\n\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n }\n}\n","import { Subject, SubjectSubscriber } from '../Subject';\nimport { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { TeardownLogic } from '../types';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\n\n/**\n * @class ConnectableObservable\n */\nexport class ConnectableObservable extends Observable {\n\n protected _subject: Subject;\n protected _refCount: number = 0;\n protected _connection: Subscription;\n /** @internal */\n _isComplete = false;\n\n constructor(public source: Observable,\n protected subjectFactory: () => Subject) {\n super();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber) {\n return this.getSubject().subscribe(subscriber);\n }\n\n protected getSubject(): Subject {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject;\n }\n\n connect(): Subscription {\n let connection = this._connection;\n if (!connection) {\n this._isComplete = false;\n connection = this._connection = new Subscription();\n connection.add(this.source\n .subscribe(new ConnectableSubscriber(this.getSubject(), this)));\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n\n refCount(): Observable {\n return higherOrderRefCount()(this) as Observable;\n }\n}\n\nconst connectableProto = ConnectableObservable.prototype;\n\nexport const connectableObservableDescriptor: PropertyDescriptorMap = {\n operator: { value: null },\n _refCount: { value: 0, writable: true },\n _subject: { value: null, writable: true },\n _connection: { value: null, writable: true },\n _subscribe: { value: connectableProto._subscribe },\n _isComplete: { value: connectableProto._isComplete, writable: true },\n getSubject: { value: connectableProto.getSubject },\n connect: { value: connectableProto.connect },\n refCount: { value: connectableProto.refCount }\n};\n\nclass ConnectableSubscriber extends SubjectSubscriber {\n constructor(destination: Subject,\n private connectable: ConnectableObservable) {\n super(destination);\n }\n protected _error(err: any): void {\n this._unsubscribe();\n super._error(err);\n }\n protected _complete(): void {\n this.connectable._isComplete = true;\n this._unsubscribe();\n super._complete();\n }\n protected _unsubscribe() {\n const connectable = this.connectable;\n if (connectable) {\n this.connectable = null;\n const connection = connectable._connection;\n connectable._refCount = 0;\n connectable._subject = null;\n connectable._connection = null;\n if (connection) {\n connection.unsubscribe();\n }\n }\n }\n}\n\nclass RefCountOperator implements Operator {\n constructor(private connectable: ConnectableObservable) {\n }\n call(subscriber: Subscriber, source: any): TeardownLogic {\n\n const { connectable } = this;\n ( connectable)._refCount++;\n\n const refCounter = new RefCountSubscriber(subscriber, connectable);\n const subscription = source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n ( refCounter).connection = connectable.connect();\n }\n\n return subscription;\n }\n}\n\nclass RefCountSubscriber extends Subscriber {\n\n private connection: Subscription;\n\n constructor(destination: Subscriber,\n private connectable: ConnectableObservable) {\n super(destination);\n }\n\n protected _unsubscribe() {\n\n const { connectable } = this;\n if (!connectable) {\n this.connection = null;\n return;\n }\n\n this.connectable = null;\n const refCount = ( connectable)._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n\n ( connectable)._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // ).subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n const { connection } = this;\n const sharedConnection = ( connectable)._connection;\n this.connection = null;\n\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function groupBy(keySelector: (value: T) => K): OperatorFunction>;\nexport function groupBy(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable) => Observable): OperatorFunction>;\nexport function groupBy(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable) => Observable): OperatorFunction>;\nexport function groupBy(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable) => Observable, subjectSelector?: () => Subject): OperatorFunction>;\n/* tslint:enable:max-line-length */\n\n/**\n * Groups the items emitted by an Observable according to a specified criterion,\n * and emits these grouped items as `GroupedObservables`, one\n * {@link GroupedObservable} per group.\n *\n * ![](groupBy.png)\n *\n * When the Observable emits an item, a key is computed for this item with the keySelector function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Elsewhere, a new\n * {@link GroupedObservable} for this key is created and emits.\n *\n * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common\n * key is available as the key field of a {@link GroupedObservable} instance.\n *\n * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements\n * returned by the elementSelector function.\n *\n * ## Examples\n *\n * ### Group objects by id and return as array\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { mergeMap, groupBy, reduce } from 'rxjs/operators';\n *\n * of(\n * {id: 1, name: 'JavaScript'},\n * {id: 2, name: 'Parcel'},\n * {id: 2, name: 'webpack'},\n * {id: 1, name: 'TypeScript'},\n * {id: 3, name: 'TSLint'}\n * ).pipe(\n * groupBy(p => p.id),\n * mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // [ { id: 1, name: 'JavaScript'},\n * // { id: 1, name: 'TypeScript'} ]\n * //\n * // [ { id: 2, name: 'Parcel'},\n * // { id: 2, name: 'webpack'} ]\n * //\n * // [ { id: 3, name: 'TSLint'} ]\n * ```\n *\n * ### Pivot data on the id field\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';\n *\n * of(\n * { id: 1, name: 'JavaScript' },\n * { id: 2, name: 'Parcel' },\n * { id: 2, name: 'webpack' },\n * { id: 1, name: 'TypeScript' },\n * { id: 3, name: 'TSLint' }\n * )\n * .pipe(\n * groupBy(p => p.id, p => p.name),\n * mergeMap(group$ =>\n * group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))\n * ),\n * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }\n * // { id: 2, values: [ 'Parcel', 'webpack' ] }\n * // { id: 3, values: [ 'TSLint' ] }\n * ```\n *\n * @param {function(value: T): K} keySelector A function that extracts the key\n * for each item.\n * @param {function(value: T): R} [elementSelector] A function that extracts the\n * return element for each item.\n * @param {function(grouped: GroupedObservable): Observable} [durationSelector]\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @return {Observable>} An Observable that emits\n * GroupedObservables, each of which corresponds to a unique key value and each\n * of which emits those items from the source Observable that share that key\n * value.\n * @method groupBy\n * @owner Observable\n */\nexport function groupBy(keySelector: (value: T) => K,\n elementSelector?: ((value: T) => R) | void,\n durationSelector?: (grouped: GroupedObservable) => Observable,\n subjectSelector?: () => Subject): OperatorFunction> {\n return (source: Observable) =>\n source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));\n}\n\nexport interface RefCountSubscription {\n count: number;\n unsubscribe: () => void;\n closed: boolean;\n attemptedToUnsubscribe: boolean;\n}\n\nclass GroupByOperator implements Operator> {\n constructor(private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable) => Observable,\n private subjectSelector?: () => Subject) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new GroupBySubscriber(\n subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupBySubscriber extends Subscriber implements RefCountSubscription {\n private groups: Map> = null;\n public attemptedToUnsubscribe: boolean = false;\n public count: number = 0;\n\n constructor(destination: Subscriber>,\n private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable) => Observable,\n private subjectSelector?: () => Subject) {\n super(destination);\n }\n\n protected _next(value: T): void {\n let key: K;\n try {\n key = this.keySelector(value);\n } catch (err) {\n this.error(err);\n return;\n }\n\n this._group(value, key);\n }\n\n private _group(value: T, key: K) {\n let groups = this.groups;\n\n if (!groups) {\n groups = this.groups = new Map>();\n }\n\n let group = groups.get(key);\n\n let element: R;\n if (this.elementSelector) {\n try {\n element = this.elementSelector(value);\n } catch (err) {\n this.error(err);\n }\n } else {\n element = value;\n }\n\n if (!group) {\n group = (this.subjectSelector ? this.subjectSelector() : new Subject()) as Subject;\n groups.set(key, group);\n const groupedObservable = new GroupedObservable(key, group, this);\n this.destination.next(groupedObservable);\n if (this.durationSelector) {\n let duration: any;\n try {\n duration = this.durationSelector(new GroupedObservable(key, >group));\n } catch (err) {\n this.error(err);\n return;\n }\n this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));\n }\n }\n\n if (!group.closed) {\n group.next(element);\n }\n }\n\n protected _error(err: any): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.error(err);\n });\n\n groups.clear();\n }\n this.destination.error(err);\n }\n\n protected _complete(): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.complete();\n });\n\n groups.clear();\n }\n this.destination.complete();\n }\n\n removeGroup(key: K): void {\n this.groups.delete(key);\n }\n\n unsubscribe() {\n if (!this.closed) {\n this.attemptedToUnsubscribe = true;\n if (this.count === 0) {\n super.unsubscribe();\n }\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupDurationSubscriber extends Subscriber {\n constructor(private key: K,\n private group: Subject,\n private parent: GroupBySubscriber) {\n super(group);\n }\n\n protected _next(value: T): void {\n this.complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { parent, key } = this;\n this.key = this.parent = null;\n if (parent) {\n parent.removeGroup(key);\n }\n }\n}\n\n/**\n * An Observable representing values belonging to the same group represented by\n * a common key. The values emitted by a GroupedObservable come from the source\n * Observable. The common key is available as the field `key` on a\n * GroupedObservable instance.\n *\n * @class GroupedObservable\n */\nexport class GroupedObservable extends Observable {\n /** @deprecated Do not construct this type. Internal use only */\n constructor(public key: K,\n private groupSubject: Subject,\n private refCountSubscription?: RefCountSubscription) {\n super();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber) {\n const subscription = new Subscription();\n const { refCountSubscription, groupSubject } = this;\n if (refCountSubscription && !refCountSubscription.closed) {\n subscription.add(new InnerRefCountSubscription(refCountSubscription));\n }\n subscription.add(groupSubject.subscribe(subscriber));\n return subscription;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass InnerRefCountSubscription extends Subscription {\n constructor(private parent: RefCountSubscription) {\n super();\n parent.count++;\n }\n\n unsubscribe() {\n const parent = this.parent;\n if (!parent.closed && !this.closed) {\n super.unsubscribe();\n parent.count -= 1;\n if (parent.count === 0 && parent.attemptedToUnsubscribe) {\n parent.unsubscribe();\n }\n }\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { SubscriptionLike } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n *\n * @class BehaviorSubject\n */\nexport class BehaviorSubject extends Subject {\n\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber): Subscription {\n const subscription = super._subscribe(subscriber);\n if (subscription && !(subscription).closed) {\n subscriber.next(this._value);\n }\n return subscription;\n }\n\n getValue(): T {\n if (this.hasError) {\n throw this.thrownError;\n } else if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else {\n return this._value;\n }\n }\n\n next(value: T): void {\n super.next(this._value = value);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n *\n * @class Action\n */\nexport class Action extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler.\n * @return {void}\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsyncAction extends Action {\n\n public id: any;\n public state: T;\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler,\n protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, id?: any, delay: number = 0): any {\n return setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(scheduler: AsyncScheduler, id: any, delay: number = 0): any {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay !== null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n clearInterval(id);\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n * @return {any}\n */\n public execute(state: T, delay: number): any {\n\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, delay: number): any {\n let errored: boolean = false;\n let errorValue: any = undefined;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n errorValue = !!e && e || new Error(e);\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n\n const id = this.id;\n const scheduler = this.scheduler;\n const actions = scheduler.actions;\n const index = actions.indexOf(this);\n\n this.work = null;\n this.state = null;\n this.pending = false;\n this.scheduler = null;\n\n if (index !== -1) {\n actions.splice(index, 1);\n }\n\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class QueueAction extends AsyncAction {\n\n constructor(protected scheduler: QueueScheduler,\n protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return (delay > 0 || this.closed) ?\n super.execute(state, delay) :\n this._execute(state, delay) ;\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: any, delay: number = 0): any {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Otherwise flush the scheduler starting with this action.\n return scheduler.flush(this);\n }\n}\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @class Scheduler\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}\n */\nexport class Scheduler implements SchedulerLike {\n\n /**\n * Note: the extra arrow function wrapper is to make testing by overriding\n * Date.now easier.\n * @nocollapse\n */\n public static now: () => number = () => Date.now();\n\n constructor(private SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return {number} A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param {function(state: ?T): ?Subscription} work A function representing a\n * task, or some unit of work to be executed by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler itself.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @return {Subscription} A subscription in order to be able to unsubscribe\n * the scheduled work.\n */\n public schedule(work: (this: SchedulerAction, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.SchedulerAction(this, work).schedule(state, delay);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport class AsyncScheduler extends Scheduler {\n public static delegate?: Scheduler;\n public actions: Array> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @type {boolean}\n * @deprecated internal use only\n */\n public active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @type {any}\n * @deprecated internal use only\n */\n public scheduled: any = undefined;\n\n constructor(SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n super(SchedulerAction, () => {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.now();\n } else {\n return now();\n }\n });\n }\n\n public schedule(work: (this: SchedulerAction, state?: T) => void, delay: number = 0, state?: T): Subscription {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.schedule(work, delay, state);\n } else {\n return super.schedule(work, delay, state);\n }\n }\n\n public flush(action: AsyncAction): void {\n\n const {actions} = this;\n\n if (this.active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this.active = true;\n\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (action = actions.shift()); // exhaust the scheduler queue\n\n this.active = false;\n\n if (error) {\n while (action = actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * Put every next task on a queue, instead of executing it immediately\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n *\n * @static true\n * @name queue\n * @owner Scheduler\n */\n\nexport const queue = new QueueScheduler(QueueAction);\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * The same Observable instance returned by any call to {@link empty} without a\n * `scheduler`. It is preferrable to use this over `empty()`.\n */\nexport const EMPTY = new Observable(subscriber => subscriber.complete());\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * Just emits 'complete', and nothing else.\n * \n *\n * ![](empty.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the complete notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then complete\n * ```ts\n * import { empty } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * const result = empty().pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c'\n * ```ts\n * import { empty, interval } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * const interval$ = interval(1000);\n * result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : empty()),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval eg(0,1,2,3,...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1 print abc\n * // if x % 2 is not equal to 1 nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link never}\n * @see {@link of}\n * @see {@link throwError}\n *\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @return An \"empty\" Observable: emits only the complete\n * notification.\n * @deprecated Deprecated in favor of using {@link EMPTY} constant, or {@link scheduled} (e.g. `scheduled([], scheduler)`)\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable(subscriber => scheduler.schedule(() => subscriber.complete()));\n}\n","import { SchedulerLike } from '../types';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && typeof (value).schedule === 'function';\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = (array: ArrayLike) => (subscriber: Subscriber) => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray(input: ArrayLike, scheduler: SchedulerLike) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\nexport function fromArray(input: ArrayLike, scheduler?: SchedulerLike) {\n if (!scheduler) {\n return new Observable(subscribeToArray(input));\n } else {\n return scheduleArray(input, scheduler);\n }\n}\n","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { Observable } from '../Observable';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler: SchedulerLike):\n Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler: SchedulerLike):\n Observable;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler: SchedulerLike):\n Observable;\nexport function of(...args: (T | SchedulerLike)[]): Observable;\n\n// TODO(benlesh): Update the typings for this when we can switch to TS 3.x\nexport function of(a: T): Observable;\nexport function of(a: T, b: T2): Observable;\nexport function of(a: T, b: T2, c: T3): Observable;\nexport function of(a: T, b: T2, c: T3, d: T4): Observable;\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5): Observable;\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6): Observable;\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7):\n Observable;\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8):\n Observable;\nexport function of(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9):\n Observable;\nexport function of(...args: T[]): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * Each argument becomes a `next` notification.\n *\n * ![](of.png)\n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: 10'\n * // 'next: 20'\n * // 'next: 30'\n *\n * ```\n *\n * Emit the array `[1,2,3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1,2,3])\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: [1,2,3]'\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param {...T} values A comma separated list of arguments you want to be emitted\n * @return {Observable} An Observable that emits the arguments\n * described above and then completes.\n * @method of\n * @owner Observable\n */\n\nexport function of(...args: Array): Observable {\n let scheduler = args[args.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n args.pop();\n return scheduleArray(args as T[], scheduler);\n } else {\n return fromArray(args as T[]);\n }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits an error notification.\n *\n * Just emits 'error', and nothing else.\n * \n *\n * ![](throw.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the error notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then emit an error\n * ```ts\n * import { throwError, concat, of } from 'rxjs';\n *\n * const result = concat(of(7), throwError(new Error('oops!')));\n * result.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // 7\n * // Error: oops!\n * ```\n *\n * ---\n *\n * ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2\n * ```ts\n * import { throwError, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * interval(1000).pipe(\n * mergeMap(x => x === 2\n * ? throwError('Twos are bad')\n * : of('a', 'b', 'c')\n * ),\n * ).subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // a\n * // b\n * // c\n * // a\n * // b\n * // c\n * // Twos are bad\n * ```\n *\n * @see {@link Observable}\n * @see {@link empty}\n * @see {@link never}\n * @see {@link of}\n *\n * @param {any} error The particular Error to pass to the error notification.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emission of the error notification.\n * @return {Observable} An error Observable: emits only the error notification\n * using the given error argument.\n * @static true\n * @name throwError\n * @owner Observable\n */\nexport function throwError(error: any, scheduler?: SchedulerLike): Observable {\n if (!scheduler) {\n return new Observable(subscriber => subscriber.error(error));\n } else {\n return new Observable(subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));\n }\n}\n\ninterface DispatchArg {\n error: any;\n subscriber: Subscriber;\n}\n\nfunction dispatch({ error, subscriber }: DispatchArg) {\n subscriber.error(error);\n}\n","import { PartialObserver } from './types';\nimport { Observable } from './Observable';\nimport { empty } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { deprecate } from 'util';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated NotificationKind is deprecated as const enums are not compatible with isolated modules. Use a string literal instead.\n */\nexport enum NotificationKind {\n NEXT = 'N',\n ERROR = 'E',\n COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n *\n * @class Notification\n */\nexport class Notification {\n hasValue: boolean;\n\n constructor(public kind: 'N' | 'E' | 'C', public value?: T, public error?: any) {\n this.hasValue = kind === 'N';\n }\n\n /**\n * Delivers to the given `observer` the value wrapped by this Notification.\n * @param {Observer} observer\n * @return\n */\n observe(observer: PartialObserver): any {\n switch (this.kind) {\n case 'N':\n return observer.next && observer.next(this.value);\n case 'E':\n return observer.error && observer.error(this.error);\n case 'C':\n return observer.complete && observer.complete();\n }\n }\n\n /**\n * Given some {@link Observer} callbacks, deliver the value represented by the\n * current Notification to the correctly corresponding callback.\n * @param {function(value: T): void} next An Observer `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return next && next(this.value);\n case 'E':\n return error && error(this.error);\n case 'C':\n return complete && complete();\n }\n }\n\n /**\n * Takes an Observer or its individual callback functions, and calls `observe`\n * or `do` methods accordingly.\n * @param {Observer|function(value: T): void} nextOrObserver An Observer or\n * the `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n accept(nextOrObserver: PartialObserver | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n if (nextOrObserver && typeof (>nextOrObserver).next === 'function') {\n return this.observe(>nextOrObserver);\n } else {\n return this.do(<(value: T) => void>nextOrObserver, error, complete);\n }\n }\n\n /**\n * Returns a simple Observable that just delivers the notification represented\n * by this Notification instance.\n * @return {any}\n */\n toObservable(): Observable {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return of(this.value);\n case 'E':\n return throwError(this.error);\n case 'C':\n return empty();\n }\n throw new Error('unexpected notification kind value');\n }\n\n private static completeNotification: Notification = new Notification('C');\n private static undefinedValueNotification: Notification = new Notification('N', undefined);\n\n /**\n * A shortcut to create a Notification instance of the type `next` from a\n * given value.\n * @param {T} value The `next` value.\n * @return {Notification} The \"next\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createNext(value: T): Notification {\n if (typeof value !== 'undefined') {\n return new Notification('N', value);\n }\n return Notification.undefinedValueNotification;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `error` from a\n * given error.\n * @param {any} [err] The `error` error.\n * @return {Notification} The \"error\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createError(err?: any): Notification {\n return new Notification('E', undefined, err);\n }\n\n /**\n * A shortcut to create a Notification instance of the type `complete`.\n * @return {Notification} The valueless \"complete\" Notification.\n * @nocollapse\n */\n static createComplete(): Notification {\n return Notification.completeNotification;\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n *\n * Re-emits all notifications from source Observable with specified scheduler.\n *\n * Ensure a specific scheduler is used, from outside of an Observable.\n *\n * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule\n * notifications emitted by the source Observable. It might be useful, if you do not have control over\n * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.\n *\n * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,\n * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal\n * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits\n * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.\n * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split\n * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source\n * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a\n * little bit more, to ensure that they are emitted at expected moments.\n *\n * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications\n * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`\n * will delay all notifications - including error notifications - while `delay` will pass through error\n * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator\n * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used\n * for notification emissions in general.\n *\n * ## Example\n * Ensure values in subscribe are called just before browser repaint.\n * ```ts\n * import { interval } from 'rxjs';\n * import { observeOn } from 'rxjs/operators';\n *\n * const intervals = interval(10); // Intervals are scheduled\n * // with async scheduler by default...\n * intervals.pipe(\n * observeOn(animationFrameScheduler), // ...but we will observe on animationFrame\n * ) // scheduler to ensure smooth animation.\n * .subscribe(val => {\n * someDiv.style.height = val + 'px';\n * });\n * ```\n *\n * @see {@link delay}\n *\n * @param {SchedulerLike} scheduler Scheduler that will be used to reschedule notifications from source Observable.\n * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.\n * @return {Observable} Observable that emits the same notifications as the source Observable,\n * but with provided scheduler.\n *\n * @method observeOn\n * @owner Observable\n */\nexport function observeOn(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction {\n return function observeOnOperatorFunction(source: Observable): Observable {\n return source.lift(new ObserveOnOperator(scheduler, delay));\n };\n}\n\nexport class ObserveOnOperator implements Operator {\n constructor(private scheduler: SchedulerLike, private delay: number = 0) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ObserveOnSubscriber extends Subscriber {\n /** @nocollapse */\n static dispatch(this: SchedulerAction, arg: ObserveOnMessage) {\n const { notification, destination } = arg;\n notification.observe(destination);\n this.unsubscribe();\n }\n\n constructor(destination: Subscriber,\n private scheduler: SchedulerLike,\n private delay: number = 0) {\n super(destination);\n }\n\n private scheduleMessage(notification: Notification): void {\n const destination = this.destination as Subscription;\n destination.add(this.scheduler.schedule(\n ObserveOnSubscriber.dispatch,\n this.delay,\n new ObserveOnMessage(notification, this.destination)\n ));\n }\n\n protected _next(value: T): void {\n this.scheduleMessage(Notification.createNext(value));\n }\n\n protected _error(err: any): void {\n this.scheduleMessage(Notification.createError(err));\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.scheduleMessage(Notification.createComplete());\n this.unsubscribe();\n }\n}\n\nexport class ObserveOnMessage {\n constructor(public notification: Notification,\n public destination: PartialObserver) {\n }\n}\n","import { Subject } from './Subject';\nimport { SchedulerLike } from './types';\nimport { queue } from './scheduler/queue';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { ObserveOnSubscriber } from './operators/observeOn';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\n/**\n * A variant of Subject that \"replays\" or emits old values to new subscribers.\n * It buffers a set number of values and will emit those values immediately to\n * any new subscribers in addition to emitting new values to existing subscribers.\n *\n * @class ReplaySubject\n */\nexport class ReplaySubject extends Subject {\n private _events: (ReplayEvent | T)[] = [];\n private _bufferSize: number;\n private _windowTime: number;\n private _infiniteTimeWindow: boolean = false;\n\n constructor(bufferSize: number = Number.POSITIVE_INFINITY,\n windowTime: number = Number.POSITIVE_INFINITY,\n private scheduler?: SchedulerLike) {\n super();\n this._bufferSize = bufferSize < 1 ? 1 : bufferSize;\n this._windowTime = windowTime < 1 ? 1 : windowTime;\n\n if (windowTime === Number.POSITIVE_INFINITY) {\n this._infiniteTimeWindow = true;\n this.next = this.nextInfiniteTimeWindow;\n } else {\n this.next = this.nextTimeWindow;\n }\n }\n\n private nextInfiniteTimeWindow(value: T): void {\n const _events = this._events;\n _events.push(value);\n // Since this method is invoked in every next() call than the buffer\n // can overgrow the max size only by one item\n if (_events.length > this._bufferSize) {\n _events.shift();\n }\n\n super.next(value);\n }\n\n private nextTimeWindow(value: T): void {\n this._events.push(new ReplayEvent(this._getNow(), value));\n this._trimBufferThenGetEvents();\n\n super.next(value);\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber): Subscription {\n // When `_infiniteTimeWindow === true` then the buffer is already trimmed\n const _infiniteTimeWindow = this._infiniteTimeWindow;\n const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();\n const scheduler = this.scheduler;\n const len = _events.length;\n let subscription: Subscription;\n\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else if (this.isStopped || this.hasError) {\n subscription = Subscription.EMPTY;\n } else {\n this.observers.push(subscriber);\n subscription = new SubjectSubscription(this, subscriber);\n }\n\n if (scheduler) {\n subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));\n }\n\n if (_infiniteTimeWindow) {\n for (let i = 0; i < len && !subscriber.closed; i++) {\n subscriber.next(_events[i]);\n }\n } else {\n for (let i = 0; i < len && !subscriber.closed; i++) {\n subscriber.next((>_events[i]).value);\n }\n }\n\n if (this.hasError) {\n subscriber.error(this.thrownError);\n } else if (this.isStopped) {\n subscriber.complete();\n }\n\n return subscription;\n }\n\n _getNow(): number {\n return (this.scheduler || queue).now();\n }\n\n private _trimBufferThenGetEvents(): ReplayEvent[] {\n const now = this._getNow();\n const _bufferSize = this._bufferSize;\n const _windowTime = this._windowTime;\n const _events = []>this._events;\n\n const eventsCount = _events.length;\n let spliceCount = 0;\n\n // Trim events that fall out of the time window.\n // Start at the front of the list. Break early once\n // we encounter an event that falls within the window.\n while (spliceCount < eventsCount) {\n if ((now - _events[spliceCount].time) < _windowTime) {\n break;\n }\n spliceCount++;\n }\n\n if (eventsCount > _bufferSize) {\n spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);\n }\n\n if (spliceCount > 0) {\n _events.splice(0, spliceCount);\n }\n\n return _events;\n }\n\n}\n\nclass ReplayEvent {\n constructor(public time: number, public value: T) {\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n *\n * @class AsyncSubject\n */\nexport class AsyncSubject extends Subject {\n private value: T = null;\n private hasNext: boolean = false;\n private hasCompleted: boolean = false;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber): Subscription {\n if (this.hasError) {\n subscriber.error(this.thrownError);\n return Subscription.EMPTY;\n } else if (this.hasCompleted && this.hasNext) {\n subscriber.next(this.value);\n subscriber.complete();\n return Subscription.EMPTY;\n }\n return super._subscribe(subscriber);\n }\n\n next(value: T): void {\n if (!this.hasCompleted) {\n this.value = value;\n this.hasNext = true;\n }\n }\n\n error(error: any): void {\n if (!this.hasCompleted) {\n super.error(error);\n }\n }\n\n complete(): void {\n this.hasCompleted = true;\n if (this.hasNext) {\n super.next(this.value);\n }\n super.complete();\n }\n}\n","let nextHandle = 1;\n\nconst tasksByHandle: { [handle: string]: () => void } = {};\n\nfunction runIfPresent(handle: number) {\n const cb = tasksByHandle[handle];\n if (cb) {\n cb();\n }\n}\n\nexport const Immediate = {\n setImmediate(cb: () => void): number {\n const handle = nextHandle++;\n tasksByHandle[handle] = cb;\n Promise.resolve().then(() => runIfPresent(handle));\n return handle;\n },\n\n clearImmediate(handle: number): void {\n delete tasksByHandle[handle];\n },\n};\n","import { Immediate } from '../util/Immediate';\nimport { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsapAction extends AsyncAction {\n\n constructor(protected scheduler: AsapScheduler,\n protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If a microtask has already been scheduled, don't schedule another\n // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n // the current scheduled microtask id.\n return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(\n scheduler.flush.bind(scheduler, null)\n ));\n }\n protected recycleAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue is empty, cancel the requested microtask and\n // set the scheduled flag to undefined so the next AsapAction will schedule\n // its own.\n if (scheduler.actions.length === 0) {\n Immediate.clearImmediate(id);\n scheduler.scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n\n this.active = true;\n this.scheduled = undefined;\n\n const {actions} = this;\n let error: any;\n let index: number = -1;\n let count: number = actions.length;\n action = action || actions.shift();\n\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (++index < count && (action = actions.shift()));\n\n this.active = false;\n\n if (error) {\n while (++index < count && (action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * Perform task as fast as it can be performed asynchronously\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n * @static true\n * @name asap\n * @owner Scheduler\n */\n\nexport const asap = new AsapScheduler(AsapAction);\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * Schedule task as if you used setTimeout(task, duration)\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n *\n * @static true\n * @name async\n * @owner Scheduler\n */\n\nexport const async = new AsyncScheduler(AsyncAction);\n","import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AnimationFrameAction extends AsyncAction {\n\n constructor(protected scheduler: AnimationFrameScheduler,\n protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: any, delay: number = 0): any {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(\n () => scheduler.flush(null)));\n }\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: any, delay: number = 0): any {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue is empty, cancel the requested animation frame and\n // set the scheduled flag to undefined so the next AnimationFrameAction will\n // request its own.\n if (scheduler.actions.length === 0) {\n cancelAnimationFrame(id);\n scheduler.scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n\n this.active = true;\n this.scheduled = undefined;\n\n const {actions} = this;\n let error: any;\n let index: number = -1;\n let count: number = actions.length;\n action = action || actions.shift();\n\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (++index < count && (action = actions.shift()));\n\n this.active = false;\n\n if (error) {\n while (++index < count && (action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * Perform task when `window.requestAnimationFrame` would fire\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html:
\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n *\n * @static true\n * @name animationFrame\n * @owner Scheduler\n */\n\nexport const animationFrame = new AnimationFrameScheduler(AnimationFrameAction);\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n\n protected static frameTimeFactor: number = 10;\n\n public frame: number = 0;\n public index: number = -1;\n\n constructor(SchedulerAction: typeof AsyncAction = VirtualAction as any,\n public maxFrames: number = Number.POSITIVE_INFINITY) {\n super(SchedulerAction, () => this.frame);\n }\n\n /**\n * Prompt the Scheduler to execute all of its queued actions, therefore\n * clearing its queue.\n * @return {void}\n */\n public flush(): void {\n\n const {actions, maxFrames} = this;\n let error: any, action: AsyncAction;\n\n while ((action = actions[0]) && action.delay <= maxFrames) {\n actions.shift();\n this.frame = action.delay;\n\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n }\n\n if (error) {\n while (action = actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @nodoc\n */\nexport class VirtualAction extends AsyncAction {\n\n protected active: boolean = true;\n\n constructor(protected scheduler: VirtualTimeScheduler,\n protected work: (this: SchedulerAction, state?: T) => void,\n protected index: number = scheduler.index += 1) {\n super(scheduler, work);\n this.index = scheduler.index = index;\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (!this.id) {\n return super.schedule(state, delay);\n }\n this.active = false;\n // If an action is rescheduled, we save allocations by mutating its state,\n // pushing it to the end of the scheduler queue, and recycling the action.\n // But since the VirtualTimeScheduler is used for testing, VirtualActions\n // must be immutable so they can be inspected later.\n const action = new VirtualAction(this.scheduler, this.work);\n this.add(action);\n return action.schedule(state, delay);\n }\n\n protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {\n this.delay = scheduler.frame + delay;\n const {actions} = scheduler;\n actions.push(this);\n (actions as Array>).sort(VirtualAction.sortActions);\n return true;\n }\n\n protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): any {\n return undefined;\n }\n\n protected _execute(state: T, delay: number): any {\n if (this.active === true) {\n return super._execute(state, delay);\n }\n }\n\n public static sortActions(a: VirtualAction, b: VirtualAction) {\n if (a.delay === b.delay) {\n if (a.index === b.index) {\n return 0;\n } else if (a.index > b.index) {\n return 1;\n } else {\n return -1;\n }\n } else if (a.delay > b.delay) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n","export function identity(x: T): T {\n return x;\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput } from '../types';\n\n/**\n * Tests to see if the object is an RxJS {@link Observable}\n * @param obj the object to test\n */\nexport function isObservable(obj: any): obj is Observable {\n return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));\n}\n","export interface ArgumentOutOfRangeError extends Error {\n}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n new(): ArgumentOutOfRangeError;\n}\n\nfunction ArgumentOutOfRangeErrorImpl(this: any) {\n Error.call(this);\n this.message = 'argument out of range';\n this.name = 'ArgumentOutOfRangeError';\n return this;\n}\n\nArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n *\n * @class ArgumentOutOfRangeError\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = ArgumentOutOfRangeErrorImpl as any;","export interface EmptyError extends Error {\n}\n\nexport interface EmptyErrorCtor {\n new(): EmptyError;\n}\n\nfunction EmptyErrorImpl(this: any) {\n Error.call(this);\n this.message = 'no elements in sequence';\n this.name = 'EmptyError';\n return this;\n}\n\nEmptyErrorImpl.prototype = Object.create(Error.prototype);\n\n/**\n * An error thrown when an Observable or a sequence was queried but has no\n * elements.\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link single}\n *\n * @class EmptyError\n */\nexport const EmptyError: EmptyErrorCtor = EmptyErrorImpl as any;","export interface TimeoutError extends Error {\n}\n\nexport interface TimeoutErrorCtor {\n new(): TimeoutError;\n}\n\nfunction TimeoutErrorImpl(this: any) {\n Error.call(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n return this;\n}\n\nTimeoutErrorImpl.prototype = Object.create(Error.prototype);\n\n/**\n * An error thrown when duetime elapses.\n *\n * @see {@link operators/timeout}\n *\n * @class TimeoutError\n */\nexport const TimeoutError: TimeoutErrorCtor = TimeoutErrorImpl as any;\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction {\n return function mapOperation(source: Observable): Observable {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\n\nexport class MapOperator implements Operator {\n constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber extends Subscriber {\n count: number = 0;\n private thisArg: any;\n\n constructor(destination: Subscriber,\n private project: (value: T, index: number) => R,\n thisArg: any) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n // NOTE: This looks unoptimized, but it's actually purposefully NOT\n // using try/catch optimizations.\n protected _next(value: T) {\n let result: any;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { SchedulerLike, SchedulerAction } from '../types';\nimport { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { Subscriber } from '../Subscriber';\nimport { map } from '../operators/map';\nimport { canReportError } from '../util/canReportError';\nimport { isArray } from '../util/isArray';\nimport { isScheduler } from '../util/isScheduler';\n\n// tslint:disable:max-line-length\n/** @deprecated resultSelector is no longer supported, use a mapping function. */\nexport function bindCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable;\n\nexport function bindCallback(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): () => Observable;\nexport function bindCallback(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable;\nexport function bindCallback(callbackFunc: (callback: () => any) => any, scheduler?: SchedulerLike): () => Observable;\n\nexport function bindCallback(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (arg1: A1, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable;\n\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable;\n\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable;\n\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable;\n\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable;\nexport function bindCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable;\n\nexport function bindCallback(callbackFunc: (...args: Array any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable;\nexport function bindCallback(callbackFunc: (...args: Array any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable;\n\nexport function bindCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable;\n\n// tslint:enable:max-line-length\n\n/**\n * Converts a callback API to a function that returns an Observable.\n *\n * Give it a function `f` of type `f(x, callback)` and\n * it will return a function `g` that when called as `g(x)` will output an\n * Observable.\n *\n * `bindCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters. The\n * last parameter must be a callback function that `func` calls when it is\n * done.\n *\n * The output of `bindCallback` is a function that takes the same parameters\n * as `func`, except the last one (the callback). When the output function\n * is called with arguments it will return an Observable. If function `func`\n * calls its callback with one argument, the Observable will emit that value.\n * If on the other hand the callback is called with multiple values the resulting\n * Observable will emit an array with said values as arguments.\n *\n * It is **very important** to remember that input function `func` is not called\n * when the output function is, but rather when the Observable returned by the output\n * function is subscribed. This means if `func` makes an AJAX request, that request\n * will be made every time someone subscribes to the resulting Observable, but not before.\n *\n * The last optional parameter - `scheduler` - can be used to control when the call\n * to `func` happens after someone subscribes to Observable, as well as when results\n * passed to callback will be emitted. By default, the subscription to an Observable calls `func`\n * synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,\n * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler\n * and call `subscribe` on the output Observable, all function calls that are currently executing\n * will end before `func` is invoked.\n *\n * By default, results passed to the callback are emitted immediately after `func` invokes the callback.\n * In particular, if the callback is called synchronously, then the subscription of the resulting Observable\n * will call the `next` function synchronously as well. If you want to defer that call,\n * you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can\n * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.\n *\n * Note that the Observable created by the output function will always emit a single value\n * and then complete immediately. If `func` calls the callback multiple times, values from subsequent\n * calls will not appear in the stream. If you need to listen for multiple calls,\n * you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.\n *\n * If `func` depends on some context (`this` property) and is not already bound, the context of `func`\n * will be the context that the output function has at call time. In particular, if `func`\n * is called as a method of some objec and if `func` is not already bound, in order to preserve the context\n * it is recommended that the context of the output function is set to that object as well.\n *\n * If the input function calls its callback in the \"node style\" (i.e. first argument to callback is\n * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}\n * provides convenient error handling and probably is a better choice.\n * `bindCallback` will treat such functions the same as any other and error parameters\n * (whether passed or not) will always be interpreted as regular callback argument.\n *\n * ## Examples\n *\n * ### Convert jQuery's getJSON to an Observable API\n * ```ts\n * import { bindCallback } from 'rxjs';\n * import * as jQuery from 'jquery';\n *\n * // Suppose we have jQuery.getJSON('/my/url', callback)\n * const getJSONAsObservable = bindCallback(jQuery.getJSON);\n * const result = getJSONAsObservable('/my/url');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * ### Receive an array of arguments passed to a callback\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const someFunction = (a, b, c) => {\n * console.log(a); // 5\n * console.log(b); // 'some string'\n * console.log(c); // {someProperty: 'someValue'}\n * };\n *\n * const boundSomeFunction = bindCallback(someFunction);\n * boundSomeFunction().subscribe(values => {\n * console.log(values) // [5, 'some string', {someProperty: 'someValue'}]\n * });\n * ```\n *\n * ### Compare behaviour with and without async Scheduler\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * function iCallMyCallbackSynchronously(cb) {\n * cb();\n * }\n *\n * const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);\n * const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async);\n *\n * boundSyncFn().subscribe(() => console.log('I was sync!'));\n * boundAsyncFn().subscribe(() => console.log('I was async!'));\n * console.log('This happened...');\n *\n * // Logs:\n * // I was sync!\n * // This happened...\n * // I was async!\n * ```\n *\n * ### Use bindCallback on an object method\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const boundMethod = bindCallback(someObject.methodWithCallback);\n * boundMethod.call(someObject) // make sure methodWithCallback has access to someObject\n * .subscribe(subscriber);\n * ```\n *\n * @see {@link bindNodeCallback}\n * @see {@link from}\n *\n * @param {function} func A function with a callback as the last parameter.\n * @param {SchedulerLike} [scheduler] The scheduler on which to schedule the\n * callbacks.\n * @return {function(...params: *): Observable} A function which returns the\n * Observable that delivers the same values the callback would deliver.\n * @name bindCallback\n */\nexport function bindCallback(\n callbackFunc: Function,\n resultSelector?: Function|SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable {\n if (resultSelector) {\n if (isScheduler(resultSelector)) {\n scheduler = resultSelector;\n } else {\n // DEPRECATED PATH\n return (...args: any[]) => bindCallback(callbackFunc, scheduler)(...args).pipe(\n map((args) => isArray(args) ? resultSelector(...args) : resultSelector(args)),\n );\n }\n }\n\n return function (this: any, ...args: any[]): Observable {\n const context = this;\n let subject: AsyncSubject;\n const params = {\n context,\n subject,\n callbackFunc,\n scheduler,\n };\n return new Observable(subscriber => {\n if (!scheduler) {\n if (!subject) {\n subject = new AsyncSubject();\n const handler = (...innerArgs: any[]) => {\n subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);\n subject.complete();\n };\n\n try {\n callbackFunc.apply(context, [...args, handler]);\n } catch (err) {\n if (canReportError(subject)) {\n subject.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n return subject.subscribe(subscriber);\n } else {\n const state: DispatchState = {\n args, subscriber, params,\n };\n return scheduler.schedule>(dispatch, 0, state);\n }\n });\n };\n}\n\ninterface DispatchState {\n args: any[];\n subscriber: Subscriber;\n params: ParamsContext;\n}\n\ninterface ParamsContext {\n callbackFunc: Function;\n scheduler: SchedulerLike;\n context: any;\n subject: AsyncSubject;\n}\n\nfunction dispatch(this: SchedulerAction>, state: DispatchState) {\n const self = this;\n const { args, subscriber, params } = state;\n const { callbackFunc, context, scheduler } = params;\n let { subject } = params;\n if (!subject) {\n subject = params.subject = new AsyncSubject();\n\n const handler = (...innerArgs: any[]) => {\n const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;\n this.add(scheduler.schedule>(dispatchNext, 0, { value, subject }));\n };\n\n try {\n callbackFunc.apply(context, [...args, handler]);\n } catch (err) {\n subject.error(err);\n }\n }\n\n this.add(subject.subscribe(subscriber));\n}\n\ninterface NextState {\n subject: AsyncSubject;\n value: T;\n}\n\nfunction dispatchNext(this: SchedulerAction>, state: NextState) {\n const { value, subject } = state;\n subject.next(value);\n subject.complete();\n}\n\ninterface ErrorState {\n subject: AsyncSubject;\n err: any;\n}\n\nfunction dispatchError(this: SchedulerAction>, state: ErrorState) {\n const { err, subject } = state;\n subject.error(err);\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { Subscriber } from '../Subscriber';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { map } from '../operators/map';\nimport { canReportError } from '../util/canReportError';\nimport { isScheduler } from '../util/isScheduler';\nimport { isArray } from '../util/isArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated resultSelector is deprecated, pipe to map instead */\nexport function bindNodeCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable;\n\nexport function bindNodeCallback(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable;\nexport function bindNodeCallback(callbackFunc: (callback: (err: any) => any) => any, scheduler?: SchedulerLike): () => Observable;\n\nexport function bindNodeCallback(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable;\n\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable;\n\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable;\n\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable;\n\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable;\nexport function bindNodeCallback(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable; /* tslint:enable:max-line-length */\n\nexport function bindNodeCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable;\n/**\n * Converts a Node.js-style callback API to a function that returns an\n * Observable.\n *\n * It's just like {@link bindCallback}, but the\n * callback is expected to be of type `callback(error, result)`.\n *\n * `bindNodeCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters, but the\n * last parameter must be a callback function that `func` calls when it is\n * done. The callback function is expected to follow Node.js conventions,\n * where the first argument to the callback is an error object, signaling\n * whether call was successful. If that object is passed to callback, it means\n * something went wrong.\n *\n * The output of `bindNodeCallback` is a function that takes the same\n * parameters as `func`, except the last one (the callback). When the output\n * function is called with arguments, it will return an Observable.\n * If `func` calls its callback with error parameter present, Observable will\n * error with that value as well. If error parameter is not passed, Observable will emit\n * second parameter. If there are more parameters (third and so on),\n * Observable will emit an array with all arguments, except first error argument.\n *\n * Note that `func` will not be called at the same time output function is,\n * but rather whenever resulting Observable is subscribed. By default call to\n * `func` will happen synchronously after subscription, but that can be changed\n * with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}\n * can also control when values from callback will be emitted by Observable.\n * To find out more, check out documentation for {@link bindCallback}, where\n * {@link SchedulerLike} works exactly the same.\n *\n * As in {@link bindCallback}, context (`this` property) of input function will be set to context\n * of returned function, when it is called.\n *\n * After Observable emits value, it will complete immediately. This means\n * even if `func` calls callback again, values from second and consecutive\n * calls will never appear on the stream. If you need to handle functions\n * that call callbacks multiple times, check out {@link fromEvent} or\n * {@link fromEventPattern} instead.\n *\n * Note that `bindNodeCallback` can be used in non-Node.js environments as well.\n * \"Node.js-style\" callbacks are just a convention, so if you write for\n * browsers or any other environment and API you use implements that callback style,\n * `bindNodeCallback` can be safely used on that API functions as well.\n *\n * Remember that Error object passed to callback does not have to be an instance\n * of JavaScript built-in `Error` object. In fact, it does not even have to an object.\n * Error parameter of callback function is interpreted as \"present\", when value\n * of that parameter is truthy. It could be, for example, non-zero number, non-empty\n * string or boolean `true`. In all of these cases resulting Observable would error\n * with that value. This means usually regular style callbacks will fail very often when\n * `bindNodeCallback` is used. If your Observable errors much more often then you\n * would expect, check if callback really is called in Node.js-style and, if not,\n * switch to {@link bindCallback} instead.\n *\n * Note that even if error parameter is technically present in callback, but its value\n * is falsy, it still won't appear in array emitted by Observable.\n *\n * ## Examples\n * ### Read a file from the filesystem and get the data as an Observable\n * ```ts\n * import * as fs from 'fs';\n * const readFileAsObservable = bindNodeCallback(fs.readFile);\n * const result = readFileAsObservable('./roadNames.txt', 'utf8');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * ### Use on function calling callback with multiple arguments\n * ```ts\n * someFunction((err, a, b) => {\n * console.log(err); // null\n * console.log(a); // 5\n * console.log(b); // \"some string\"\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(value => {\n * console.log(value); // [5, \"some string\"]\n * });\n * ```\n *\n * ### Use on function calling callback in regular style\n * ```ts\n * someFunction(a => {\n * console.log(a); // 5\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(\n * value => {} // never gets called\n * err => console.log(err) // 5\n * );\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link from}\n *\n * @param {function} func Function with a Node.js-style callback as the last parameter.\n * @param {SchedulerLike} [scheduler] The scheduler on which to schedule the\n * callbacks.\n * @return {function(...params: *): Observable} A function which returns the\n * Observable that delivers the same values the Node.js callback would\n * deliver.\n * @name bindNodeCallback\n */\nexport function bindNodeCallback(\n callbackFunc: Function,\n resultSelector: Function|SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable {\n\n if (resultSelector) {\n if (isScheduler(resultSelector)) {\n scheduler = resultSelector;\n } else {\n // DEPRECATED PATH\n return (...args: any[]) => bindNodeCallback(callbackFunc, scheduler)(...args).pipe(\n map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n );\n }\n }\n\n return function(this: any, ...args: any[]): Observable {\n const params: ParamsState = {\n subject: undefined,\n args,\n callbackFunc,\n scheduler,\n context: this,\n };\n return new Observable(subscriber => {\n const { context } = params;\n let { subject } = params;\n if (!scheduler) {\n if (!subject) {\n subject = params.subject = new AsyncSubject();\n const handler = (...innerArgs: any[]) => {\n const err = innerArgs.shift();\n\n if (err) {\n subject.error(err);\n return;\n }\n\n subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);\n subject.complete();\n };\n\n try {\n callbackFunc.apply(context, [...args, handler]);\n } catch (err) {\n if (canReportError(subject)) {\n subject.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n return subject.subscribe(subscriber);\n } else {\n return scheduler.schedule>(dispatch, 0, { params, subscriber, context });\n }\n });\n };\n}\n\ninterface DispatchState {\n subscriber: Subscriber;\n context: any;\n params: ParamsState;\n}\n\ninterface ParamsState {\n callbackFunc: Function;\n args: any[];\n scheduler: SchedulerLike;\n subject: AsyncSubject;\n context: any;\n}\n\nfunction dispatch(this: SchedulerAction>, state: DispatchState) {\n const { params, subscriber, context } = state;\n const { callbackFunc, args, scheduler } = params;\n let subject = params.subject;\n\n if (!subject) {\n subject = params.subject = new AsyncSubject();\n\n const handler = (...innerArgs: any[]) => {\n const err = innerArgs.shift();\n if (err) {\n this.add(scheduler.schedule>(dispatchError, 0, { err, subject }));\n } else {\n const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;\n this.add(scheduler.schedule>(dispatchNext, 0, { value, subject }));\n }\n };\n\n try {\n callbackFunc.apply(context, [...args, handler]);\n } catch (err) {\n this.add(scheduler.schedule>(dispatchError, 0, { err, subject }));\n }\n }\n\n this.add(subject.subscribe(subscriber));\n}\n\ninterface DispatchNextArg {\n subject: AsyncSubject;\n value: T;\n}\n\nfunction dispatchNext(arg: DispatchNextArg) {\n const { value, subject } = arg;\n subject.next(value);\n subject.complete();\n}\n\ninterface DispatchErrorArg {\n subject: AsyncSubject;\n err: any;\n}\n\nfunction dispatchError(arg: DispatchErrorArg) {\n const { err, subject } = arg;\n subject.error(err);\n}\n","import { Subscriber } from './Subscriber';\nimport { InnerSubscriber } from './InnerSubscriber';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class OuterSubscriber extends Subscriber {\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.destination.next(innerValue);\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this.destination.error(error);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n this.destination.complete();\n }\n}\n","import { Subscriber } from './Subscriber';\nimport { OuterSubscriber } from './OuterSubscriber';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class InnerSubscriber extends Subscriber {\n private index = 0;\n\n constructor(private parent: OuterSubscriber, public outerValue: T, public outerIndex: number) {\n super();\n }\n\n protected _next(value: R): void {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error, this);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = (promise: PromiseLike) => (subscriber: Subscriber) => {\n promise.then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = (iterable: Iterable) => (subscriber: Subscriber) => {\n const iterator = iterable[Symbol_iterator]();\n do {\n const item = iterator.next();\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n\n // Finalize the iterator if it happens to be a Generator\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n\n return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = (obj: any) => (subscriber: Subscriber) => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","export const isArrayLike = ((x: any): x is ArrayLike => x && typeof x.length === 'number' && typeof x !== 'function');","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike {\n return !!value && typeof (value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = (result: ObservableInput): (subscriber: Subscriber) => Subscription | void => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result as any);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result as Promise);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result as any);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.`\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","import { Subscription } from '../Subscription';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { Subscriber } from '../Subscriber';\nimport { subscribeTo } from './subscribeTo';\nimport { Observable } from '../Observable';\n\nexport function subscribeToResult(\n outerSubscriber: OuterSubscriber,\n result: any,\n outerValue?: T,\n outerIndex?: number,\n destination?: Subscriber\n): Subscription;\nexport function subscribeToResult(\n outerSubscriber: OuterSubscriber,\n result: any,\n outerValue?: T,\n outerIndex?: number,\n destination: Subscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex)\n): Subscription | void {\n if (destination.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(destination);\n }\n return subscribeTo(result)(destination);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { isArray } from '../util/isArray';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { Operator } from '../Operator';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { fromArray } from './fromArray';\n\nconst NONE = {};\n\n/* tslint:disable:max-line-length */\n\n// If called with a single array, it \"auto-spreads\" the array, with result selector\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, R>(sources: [O1], resultSelector: (v1: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, R>(sources: [O1, O2], resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, R>(sources: [O1, O2, O3], resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, R>(sources: [O1, O2, O3, O4], resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, R>(sources: [O1, O2, O3, O4, O5], resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput, R>(sources: [O1, O2, O3, O4, O5, O6], resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf, v6: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, R>(sources: O[], resultSelector: (...args: ObservedValueOf[]) => R, scheduler?: SchedulerLike): Observable;\n\n// standard call, but with a result selector\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, R>(v1: O1, resultSelector: (v1: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf, v6: ObservedValueOf) => R, scheduler?: SchedulerLike): Observable;\n\n// With a scheduler (deprecated)\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest>(sources: [O1], scheduler: SchedulerLike): Observable<[ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, O2 extends ObservableInput>(sources: [O1, O2], scheduler: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput>(sources: [O1, O2, O3], scheduler: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(sources: [O1, O2, O3, O4], scheduler: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(sources: [O1, O2, O3, O4, O5], scheduler: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(sources: [O1, O2, O3, O4, O5, O6], scheduler: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest>(sources: O[], scheduler: SchedulerLike): Observable[]>;\n\n// Best case\nexport function combineLatest>(sources: [O1]): Observable<[ObservedValueOf]>;\nexport function combineLatest, O2 extends ObservableInput>(sources: [O1, O2]): Observable<[ObservedValueOf, ObservedValueOf]>;\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput>(sources: [O1, O2, O3]): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(sources: [O1, O2, O3, O4]): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(sources: [O1, O2, O3, O4, O5]): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(sources: [O1, O2, O3, O4, O5, O6]): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function combineLatest>(sources: O[]): Observable[]>;\n\n// Standard calls\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest>(v1: O1, scheduler?: SchedulerLike): Observable<[ObservedValueOf]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, O2 extends ObservableInput>(v1: O1, v2: O2, scheduler?: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput>(v1: O1, v2: O2, v3: O3, scheduler?: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler?: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler?: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler?: SchedulerLike): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest>(...observables: O[]): Observable;\n\n/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */\nexport function combineLatest, R>(...observables: Array | ((...values: Array) => R)>): Observable;\n\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function combineLatest, R>(array: O[], resultSelector: (...values: ObservedValueOf[]) => R, scheduler?: SchedulerLike): Observable;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest>(...observables: Array): Observable;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest, R>(...observables: Array[]) => R) | SchedulerLike>): Observable;\n\n/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */\nexport function combineLatest(...observables: Array | ((...values: Array) => R) | SchedulerLike>): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Combines multiple Observables to create an Observable whose values are\n * calculated from the latest values of each of its input Observables.\n *\n * Whenever any input Observable emits a value, it\n * computes a formula using the latest values from all the inputs, then emits\n * the output of that formula.\n *\n * ![](combineLatest.png)\n *\n * `combineLatest` combines the values from all the Observables passed as\n * arguments. This is done by subscribing to each Observable in order and,\n * whenever any Observable emits, collecting an array of the most recent\n * values from each Observable. So if you pass `n` Observables to operator,\n * returned Observable will always emit an array of `n` values, in order\n * corresponding to order of passed Observables (value from the first Observable\n * on the first place and so on).\n *\n * Static version of `combineLatest` accepts either an array of Observables\n * or each Observable can be put directly as an argument. Note that array of\n * Observables is good choice, if you don't know beforehand how many Observables\n * you will combine. Passing empty array will result in Observable that\n * completes immediately.\n *\n * To ensure output array has always the same length, `combineLatest` will\n * actually wait for all input Observables to emit at least once,\n * before it starts emitting results. This means if some Observable emits\n * values before other Observables started emitting, all these values but the last\n * will be lost. On the other hand, if some Observable does not emit a value but\n * completes, resulting Observable will complete at the same moment without\n * emitting anything, since it will be now impossible to include value from\n * completed Observable in resulting array. Also, if some input Observable does\n * not emit any value and never completes, `combineLatest` will also never emit\n * and never complete, since, again, it will wait for all streams to emit some\n * value.\n *\n * If at least one Observable was passed to `combineLatest` and all passed Observables\n * emitted something, resulting Observable will complete when all combined\n * streams complete. So even if some Observable completes, result of\n * `combineLatest` will still emit values when other Observables do. In case\n * of completed Observable, its value from now on will always be the last\n * emitted value. On the other hand, if any Observable errors, `combineLatest`\n * will error immediately as well, and all other Observables will be unsubscribed.\n *\n * `combineLatest` accepts as optional parameter `project` function, which takes\n * as arguments all values that would normally be emitted by resulting Observable.\n * `project` can return any kind of value, which will be then emitted by Observable\n * instead of default array. Note that `project` does not take as argument that array\n * of values, but values themselves. That means default `project` can be imagined\n * as function that takes all its arguments and puts them into an array.\n *\n * ## Examples\n * ### Combine two timer Observables\n * ```ts\n * import { combineLatest, timer } from 'rxjs';\n *\n * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now\n * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now\n * const combinedTimers = combineLatest(firstTimer, secondTimer);\n * combinedTimers.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0] after 0.5s\n * // [1, 0] after 1s\n * // [1, 1] after 1.5s\n * // [2, 1] after 2s\n * ```\n *\n * ### Combine an array of Observables\n * ```ts\n * import { combineLatest, of } from 'rxjs';\n * import { delay, starWith } from 'rxjs/operators';\n *\n * const observables = [1, 5, 10].map(\n * n => of(n).pipe(\n * delay(n * 1000), // emit 0 and then emit n after n seconds\n * startWith(0),\n * )\n * );\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0, 0] immediately\n * // [1, 0, 0] after 1s\n * // [1, 5, 0] after 5s\n * // [1, 5, 10] after 10s\n * ```\n *\n *\n * ### Use project function to dynamically calculate the Body-Mass Index\n * ```ts\n * import { combineLatest, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const weight = of(70, 72, 76, 79, 75);\n * const height = of(1.76, 1.77, 1.78);\n * const bmi = combineLatest(weight, height).pipe(\n * map(([w, h]) => w / (h * h)),\n * );\n * bmi.subscribe(x => console.log('BMI is ' + x));\n *\n * // With output to console:\n * // BMI is 24.212293388429753\n * // BMI is 23.93948099205209\n * // BMI is 23.671253629592222\n * ```\n *\n * @see {@link combineAll}\n * @see {@link merge}\n * @see {@link withLatestFrom}\n *\n * @param {ObservableInput} observable1 An input Observable to combine with other Observables.\n * @param {ObservableInput} observable2 An input Observable to combine with other Observables.\n * More than one input Observables may be given as arguments\n * or an array of Observables may be given as the first argument.\n * @param {function} [project] An optional function to project the values from\n * the combined latest values into a new value on the output Observable.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to\n * each input Observable.\n * @return {Observable} An Observable of projected values from the most recent\n * values from each input Observable, or an array of the most recent values from\n * each input Observable.\n */\nexport function combineLatest, R>(\n ...observables: (O | ((...values: ObservedValueOf[]) => R) | SchedulerLike)[]\n): Observable {\n let resultSelector: (...values: Array) => R = null;\n let scheduler: SchedulerLike = null;\n\n if (isScheduler(observables[observables.length - 1])) {\n scheduler = observables.pop() as SchedulerLike;\n }\n\n if (typeof observables[observables.length - 1] === 'function') {\n resultSelector = observables.pop() as (...values: Array) => R;\n }\n\n // if the first and only other argument besides the resultSelector is an array\n // assume it's been called with `combineLatest([obs1, obs2, obs3], resultSelector)`\n if (observables.length === 1 && isArray(observables[0])) {\n observables = observables[0] as any;\n }\n\n return fromArray(observables, scheduler).lift(new CombineLatestOperator, R>(resultSelector));\n}\n\nexport class CombineLatestOperator implements Operator {\n constructor(private resultSelector?: (...values: Array) => R) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class CombineLatestSubscriber extends OuterSubscriber {\n private active: number = 0;\n private values: any[] = [];\n private observables: any[] = [];\n private toRespond: number;\n\n constructor(destination: Subscriber, private resultSelector?: (...values: Array) => R) {\n super(destination);\n }\n\n protected _next(observable: any) {\n this.values.push(NONE);\n this.observables.push(observable);\n }\n\n protected _complete() {\n const observables = this.observables;\n const len = observables.length;\n if (len === 0) {\n this.destination.complete();\n } else {\n this.active = len;\n this.toRespond = len;\n for (let i = 0; i < len; i++) {\n const observable = observables[i];\n this.add(subscribeToResult(this, observable, observable, i));\n }\n }\n }\n\n notifyComplete(unused: Subscriber): void {\n if ((this.active -= 1) === 0) {\n this.destination.complete();\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n const values = this.values;\n const oldVal = values[outerIndex];\n const toRespond = !this.toRespond\n ? 0\n : oldVal === NONE ? --this.toRespond : this.toRespond;\n values[outerIndex] = innerValue;\n\n if (toRespond === 0) {\n if (this.resultSelector) {\n this._tryResultSelector(values);\n } else {\n this.destination.next(values.slice());\n }\n }\n }\n\n private _tryResultSelector(values: any[]) {\n let result: any;\n try {\n result = this.resultSelector.apply(this, values);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable(input: InteropObservable, scheduler: SchedulerLike) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable: Subscribable = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise(input: PromiseLike, scheduler: SchedulerLike) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(\n value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n },\n err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n }\n )));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable(input: Iterable, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(subscriber => {\n const sub = new Subscription();\n let iterator: Iterator;\n sub.add(() => {\n // Finalize generators\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value: T;\n let done: boolean;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled(input: ObservableInput, scheduler: SchedulerLike): Observable {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from>(input: O): Observable>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from>(input: O, scheduler: SchedulerLike): Observable>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * Converts almost anything to an Observable.\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * iterable\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable}\n * @name from\n * @owner Observable\n */\nexport function from(input: ObservableInput, scheduler?: SchedulerLike): Observable {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n * @method mergeMap\n * @owner Observable\n */\nexport function mergeMap>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction|R> {\n if (typeof resultSelector === 'function') {\n // DEPRECATED PATH\n return (source: Observable) => source.pipe(\n mergeMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n ), concurrent)\n );\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return (source: Observable) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator implements Operator {\n constructor(private project: (value: T, index: number) => ObservableInput,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n }\n\n call(observer: Subscriber, source: any): any {\n return source.subscribe(new MergeMapSubscriber(\n observer, this.project, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber extends OuterSubscriber {\n private hasCompleted: boolean = false;\n private buffer: T[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber,\n private project: (value: T, index: number) => ObservableInput,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n\n protected _tryNext(value: T) {\n let result: ObservableInput;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.active++;\n this._innerSub(result, value, index);\n }\n\n private _innerSub(ish: ObservableInput, value: T, index: number): void {\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n subscribeToResult(this, ish, value, index, innerSubscriber);\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete();\n }\n this.unsubscribe();\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.destination.next(innerValue);\n }\n\n notifyComplete(innerSub: Subscription): void {\n const buffer = this.buffer;\n this.remove(innerSub);\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift());\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete();\n }\n }\n}\n","\nimport { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * Flattens an Observable-of-Observables.\n *\n * ![](mergeAll.png)\n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map((ev) => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { take, map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map((ev) => interval(1000).pipe(take(10))),\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits values coming from all the\n * inner Observables emitted by the source Observable.\n * @method mergeAll\n * @owner Observable\n */\nexport function mergeAll(concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction, T> {\n return mergeMap(identity, concurrent);\n}\n","\nimport { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function concatAll(): OperatorFunction, T>;\nexport function concatAll(): OperatorFunction;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.\n *\n * ![](concatAll.png)\n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, take, concatAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(ev => interval(1000).pipe(take(4))),\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaust}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable emitting values from all the inner\n * Observables concatenated.\n * @method concatAll\n * @owner Observable\n */\nexport function concatAll(): OperatorFunction, T> {\n return mergeAll(1);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { of } from './of';\nimport { from } from './from';\nimport { concatAll } from '../operators/concatAll';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat>(v1: O1, scheduler: SchedulerLike): Observable>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat, O2 extends ObservableInput>(v1: O1, v2: O2, scheduler: SchedulerLike): Observable | ObservedValueOf>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput>(v1: O1, v2: O2, v3: O3, scheduler: SchedulerLike): Observable | ObservedValueOf | ObservedValueOf>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler: SchedulerLike): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler: SchedulerLike): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler: SchedulerLike): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\n\nexport function concat>(v1: O1): Observable>;\nexport function concat, O2 extends ObservableInput>(v1: O1, v2: O2): Observable | ObservedValueOf>;\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput>(v1: O1, v2: O2, v3: O3): Observable | ObservedValueOf | ObservedValueOf>;\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\nexport function concat, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf | ObservedValueOf>;\nexport function concat>(...observables: O[]): Observable>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat>(...observables: (O | SchedulerLike)[]): Observable>;\nexport function concat(...observables: ObservableInput[]): Observable;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat(...observables: (ObservableInput | SchedulerLike)[]): Observable;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which sequentially emits all values from given\n * Observable and then moves on to the next.\n *\n * Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.\n *\n * ![](concat.png)\n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n * ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n * ```ts\n * import { concat, interval, range } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * ### Concatenate 3 Observables\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * ### Concatenate the same Observable to repeat it\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('...and it is done!')\n * );\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // \"...and it is done!\" also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n *\n * @param {ObservableInput} input1 An input Observable to concatenate with others.\n * @param {ObservableInput} input2 An input Observable to concatenate with others.\n * More than one input Observables may be given as argument.\n * @param {SchedulerLike} [scheduler=null] An optional {@link SchedulerLike} to schedule each\n * Observable subscription on.\n * @return {Observable} All values of each passed Observable merged into a\n * single Observable, in order, in serial fashion.\n * @static true\n * @name concat\n * @owner Observable\n */\nexport function concat, R>(...observables: Array): Observable | R> {\n return concatAll()(of(...observables));\n}\n","import { Observable } from '../Observable';\nimport { SubscribableOrPromise, ObservedValueOf, ObservableInput } from '../types';\nimport { from } from './from'; // lol\nimport { empty } from './empty';\n\n/**\n * Creates an Observable that, on subscribe, calls an Observable factory to\n * make an Observable for each new Observer.\n *\n * Creates the Observable lazily, that is, only when it\n * is subscribed.\n * \n *\n * ![](defer.png)\n *\n * `defer` allows you to create the Observable only when the Observer\n * subscribes, and create a fresh Observable for each Observer. It waits until\n * an Observer subscribes to it, and then it generates an Observable,\n * typically with an Observable factory function. It does this afresh for each\n * subscriber, so although each subscriber may think it is subscribing to the\n * same Observable, in fact each subscriber gets its own individual\n * Observable.\n *\n * ## Example\n * ### Subscribe to either an Observable of clicks or an Observable of interval, at random\n * ```ts\n * import { defer, fromEvent, interval } from 'rxjs';\n *\n * const clicksOrInterval = defer(function () {\n * return Math.random() > 0.5\n * ? fromEvent(document, 'click')\n * : interval(1000);\n * });\n * clicksOrInterval.subscribe(x => console.log(x));\n *\n * // Results in the following behavior:\n * // If the result of Math.random() is greater than 0.5 it will listen\n * // for clicks anywhere on the \"document\"; when document is clicked it\n * // will log a MouseEvent object to the console. If the result is less\n * // than 0.5 it will emit ascending numbers, one every second(1000ms).\n * ```\n *\n * @see {@link Observable}\n *\n * @param {function(): SubscribableOrPromise} observableFactory The Observable\n * factory function to invoke for each Observer that subscribes to the output\n * Observable. May also return a Promise, which will be converted on the fly\n * to an Observable.\n * @return {Observable} An Observable whose Observers' subscriptions trigger\n * an invocation of the given Observable factory function.\n * @static true\n * @name defer\n * @owner Observable\n */\nexport function defer>(observableFactory: () => O | void): Observable> {\n return new Observable>(subscriber => {\n let input: O | void;\n try {\n input = observableFactory();\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n const source = input ? from(input) : empty();\n return source.subscribe(subscriber);\n });\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, ObservedValuesFromArray, ObservedValueOf, SubscribableOrPromise } from '../types';\nimport { isArray } from '../util/isArray';\nimport { map } from '../operators/map';\nimport { isObject } from '../util/isObject';\nimport { isObservable } from '../util/isObservable';\nimport { from } from './from';\n\n/* tslint:disable:max-line-length */\n\n// forkJoin(a$, b$, c$)\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: SubscribableOrPromise): Observable<[T]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: ObservableInput, v2: ObservableInput): Observable<[T, T2]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput): Observable<[T, T2, T3]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): Observable<[T, T2, T3, T4]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): Observable<[T, T2, T3, T4, T5]>;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): Observable<[T, T2, T3, T4, T5, T6]>;\n\n// forkJoin([a$, b$, c$]);\n// TODO(benlesh): Uncomment for TS 3.0\n// export function forkJoin(sources: []): Observable;\nexport function forkJoin(sources: [ObservableInput]): Observable<[A]>;\nexport function forkJoin(sources: [ObservableInput, ObservableInput]): Observable<[A, B]>;\nexport function forkJoin(sources: [ObservableInput, ObservableInput, ObservableInput]): Observable<[A, B, C]>;\nexport function forkJoin(sources: [ObservableInput, ObservableInput, ObservableInput, ObservableInput]): Observable<[A, B, C, D]>;\nexport function forkJoin(sources: [ObservableInput, ObservableInput, ObservableInput, ObservableInput, ObservableInput]): Observable<[A, B, C, D, E]>;\nexport function forkJoin(sources: [ObservableInput, ObservableInput, ObservableInput, ObservableInput, ObservableInput, ObservableInput]): Observable<[A, B, C, D, E, F]>;\nexport function forkJoin[]>(sources: A): Observable[]>;\n\n// forkJoin({})\nexport function forkJoin(sourcesObject: {}): Observable;\nexport function forkJoin(sourcesObject: T): Observable<{ [K in keyof T]: ObservedValueOf }>;\n\n/** @deprecated resultSelector is deprecated, pipe to map instead */\nexport function forkJoin(...args: Array|Function>): Observable;\n/** @deprecated Use the version that takes an array of Observables instead */\nexport function forkJoin(...sources: ObservableInput[]): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns\n * an {@link Observable} that emits either an array of values in the exact same order as the passed array,\n * or a dictionary of values in the same shape as the passed dictionary.\n *\n * Wait for Observables to complete and then combine last values they emitted.\n *\n * ![](forkJoin.png)\n *\n * `forkJoin` is an operator that takes any number of input observables which can be passed either as an array\n * or a dictionary of input observables. If no input observables are provided, resulting stream will complete\n * immediately.\n *\n * `forkJoin` will wait for all passed observables to complete and then it will emit an array or an object with last\n * values from corresponding observables.\n *\n * If you pass an array of `n` observables to the operator, resulting\n * array will have `n` values, where first value is the last thing emitted by the first observable,\n * second value is the last thing emitted by the second observable and so on.\n *\n * If you pass a dictionary of observables to the operator, resulting\n * objects will have the same keys as the dictionary passed, with their last values they've emitted\n * located at the corresponding key.\n *\n * That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined\n * values not only at the end of lifecycle of passed observables, but also throughout it, try out {@link combineLatest}\n * or {@link zip} instead.\n *\n * In order for resulting array to have the same length as the number of input observables, whenever any of\n * that observables completes without emitting any value, `forkJoin` will complete at that moment as well\n * and it will not emit anything either, even if it already has some last values from other observables.\n * Conversely, if there is an observable that never completes, `forkJoin` will never complete as well,\n * unless at any point some other observable completes without emitting value, which brings us back to\n * the previous case. Overall, in order for `forkJoin` to emit a value, all observables passed as arguments\n * have to emit something at least once and complete.\n *\n * If any input observable errors at some point, `forkJoin` will error as well and all other observables\n * will be immediately unsubscribed.\n *\n * Optionally `forkJoin` accepts project function, that will be called with values which normally\n * would land in emitted array. Whatever is returned by project function, will appear in output\n * observable instead. This means that default project can be thought of as a function that takes\n * all its arguments and puts them into an array. Note that project function will be called only\n * when output observable is supposed to emit a result.\n *\n * ## Examples\n *\n * ### Use forkJoin with a dictionary of observable inputs\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin({\n * foo: of(1, 2, 3, 4),\n * bar: Promise.resolve(8),\n * baz: timer(4000),\n * });\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // { foo: 4, bar: 8, baz: 0 } after 4 seconds\n * // \"This is how it ends!\" immediately after\n * ```\n *\n * ### Use forkJoin with an array of observable inputs\n * ```ts\n * import { forkJoin, of } from 'rxjs';\n *\n * const observable = forkJoin([\n * of(1, 2, 3, 4),\n * Promise.resolve(8),\n * timer(4000),\n * ]);\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // [4, 8, 0] after 4 seconds\n * // \"This is how it ends!\" immediately after\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n *\n * @param {...ObservableInput} sources Any number of Observables provided either as an array or as an arguments\n * passed directly to the operator.\n * @param {function} [project] Function that takes values emitted by input Observables and returns value\n * that will appear in resulting Observable instead of default array.\n * @return {Observable} Observable emitting either an array of last values emitted by passed Observables\n * or value from project function.\n */\nexport function forkJoin(\n ...sources: any[]\n): Observable {\n if (sources.length === 1) {\n const first = sources[0];\n if (isArray(first)) {\n return forkJoinInternal(first, null);\n }\n // TODO(benlesh): isObservable check will not be necessary when deprecated path is removed.\n if (isObject(first) && Object.getPrototypeOf(first) === Object.prototype) {\n const keys = Object.keys(first);\n return forkJoinInternal(keys.map(key => first[key]), keys);\n }\n }\n\n // DEPRECATED PATHS BELOW HERE\n if (typeof sources[sources.length - 1] === 'function') {\n const resultSelector = sources.pop() as Function;\n sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources;\n return forkJoinInternal(sources, null).pipe(\n map((args: any[]) => resultSelector(...args))\n );\n }\n\n return forkJoinInternal(sources, null);\n}\n\nfunction forkJoinInternal(sources: ObservableInput[], keys: string[] | null): Observable {\n return new Observable(subscriber => {\n const len = sources.length;\n if (len === 0) {\n subscriber.complete();\n return;\n }\n const values = new Array(len);\n let completed = 0;\n let emitted = 0;\n for (let i = 0; i < len; i++) {\n const source = from(sources[i]);\n let hasValue = false;\n subscriber.add(source.subscribe({\n next: value => {\n if (!hasValue) {\n hasValue = true;\n emitted++;\n }\n values[i] = value;\n },\n error: err => subscriber.error(err),\n complete: () => {\n completed++;\n if (completed === len || !hasValue) {\n if (emitted === len) {\n subscriber.next(keys ?\n keys.reduce((result, key, i) => (result[key] = values[i], result), {}) :\n values);\n }\n subscriber.complete();\n }\n }\n }));\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { Subscriber } from '../Subscriber';\nimport { map } from '../operators/map';\n\nconst toString: Function = Object.prototype.toString;\n\nexport interface NodeStyleEventEmitter {\n addListener: (eventName: string | symbol, handler: NodeEventHandler) => this;\n removeListener: (eventName: string | symbol, handler: NodeEventHandler) => this;\n}\n\nexport type NodeEventHandler = (...args: any[]) => void;\n\n// For APIs that implement `addListener` and `removeListener` methods that may\n// not use the same arguments or return EventEmitter values\n// such as React Native\nexport interface NodeCompatibleEventEmitter {\n addListener: (eventName: string, handler: NodeEventHandler) => void | {};\n removeListener: (eventName: string, handler: NodeEventHandler) => void | {};\n}\n\nexport interface JQueryStyleEventEmitter {\n on: (eventName: string, handler: Function) => void;\n off: (eventName: string, handler: Function) => void;\n}\n\nexport interface HasEventTargetAddRemove {\n addEventListener(type: string, listener: ((evt: E) => void) | null, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: string, listener?: ((evt: E) => void) | null, options?: EventListenerOptions | boolean): void;\n}\n\nexport type EventTargetLike = HasEventTargetAddRemove | NodeStyleEventEmitter | NodeCompatibleEventEmitter | JQueryStyleEventEmitter;\n\nexport type FromEventTarget = EventTargetLike | ArrayLike>;\n\nexport interface EventListenerOptions {\n capture?: boolean;\n passive?: boolean;\n once?: boolean;\n}\n\nexport interface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\n/* tslint:disable:max-line-length */\nexport function fromEvent(target: FromEventTarget, eventName: string): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEvent(target: FromEventTarget, eventName: string, resultSelector: (...args: any[]) => T): Observable;\nexport function fromEvent(target: FromEventTarget, eventName: string, options: EventListenerOptions): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEvent(target: FromEventTarget, eventName: string, options: EventListenerOptions, resultSelector: (...args: any[]) => T): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable that emits events of a specific type coming from the\n * given event target.\n *\n * Creates an Observable from DOM events, or Node.js\n * EventEmitter events or others.\n *\n * ![](fromEvent.png)\n *\n * `fromEvent` accepts as a first argument event target, which is an object with methods\n * for registering event handler functions. As a second argument it takes string that indicates\n * type of event we want to listen for. `fromEvent` supports selected types of event targets,\n * which are described in detail below. If your event target does not match any of the ones listed,\n * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.\n * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event\n * handler functions have different names, but they all accept a string describing event type\n * and function itself, which will be called whenever said event happens.\n *\n * Every time resulting Observable is subscribed, event handler function will be registered\n * to event target on given event type. When that event fires, value\n * passed as a first argument to registered function will be emitted by output Observable.\n * When Observable is unsubscribed, function will be unregistered from event target.\n *\n * Note that if event target calls registered function with more than one argument, second\n * and following arguments will not appear in resulting stream. In order to get access to them,\n * you can pass to `fromEvent` optional project function, which will be called with all arguments\n * passed to event handler. Output Observable will then emit value returned by project function,\n * instead of the usual value.\n *\n * Remember that event targets listed below are checked via duck typing. It means that\n * no matter what kind of object you have and no matter what environment you work in,\n * you can safely use `fromEvent` on that object if it exposes described methods (provided\n * of course they behave as was described above). So for example if Node.js library exposes\n * event target which has the same method names as DOM EventTarget, `fromEvent` is still\n * a good choice.\n *\n * If the API you use is more callback then event handler oriented (subscribed\n * callback function fires only once and thus there is no need to manually\n * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}\n * instead.\n *\n * `fromEvent` supports following types of event targets:\n *\n * **DOM EventTarget**\n *\n * This is an object with `addEventListener` and `removeEventListener` methods.\n *\n * In the browser, `addEventListener` accepts - apart from event type string and event\n * handler function arguments - optional third parameter, which is either an object or boolean,\n * both used for additional configuration how and when passed function will be called. When\n * `fromEvent` is used with event target of that type, you can provide this values\n * as third parameter as well.\n *\n * **Node.js EventEmitter**\n *\n * An object with `addListener` and `removeListener` methods.\n *\n * **JQuery-style event target**\n *\n * An object with `on` and `off` methods\n *\n * **DOM NodeList**\n *\n * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.\n *\n * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes\n * it contains and install event handler function in every of them. When returned Observable\n * is unsubscribed, function will be removed from all Nodes.\n *\n * **DOM HtmlCollection**\n *\n * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is\n * installed and removed in each of elements.\n *\n *\n * ## Examples\n * ### Emits clicks happening on the DOM document\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * clicks.subscribe(x => console.log(x));\n *\n * // Results in:\n * // MouseEvent object logged to console every time a click\n * // occurs on the document.\n * ```\n *\n * ### Use addEventListener with capture option\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicksInDocument = fromEvent(document, 'click', true); // note optional configuration parameter\n * // which will be passed to addEventListener\n * const clicksInDiv = fromEvent(someDivInDocument, 'click');\n *\n * clicksInDocument.subscribe(() => console.log('document'));\n * clicksInDiv.subscribe(() => console.log('div'));\n *\n * // By default events bubble UP in DOM tree, so normally\n * // when we would click on div in document\n * // \"div\" would be logged first and then \"document\".\n * // Since we specified optional `capture` option, document\n * // will catch event when it goes DOWN DOM tree, so console\n * // will log \"document\" and then \"div\".\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n * @see {@link fromEventPattern}\n *\n * @param {FromEventTarget} target The DOM EventTarget, Node.js\n * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.\n * @param {string} eventName The event name of interest, being emitted by the\n * `target`.\n * @param {EventListenerOptions} [options] Options to pass through to addEventListener\n * @return {Observable}\n * @name fromEvent\n */\nexport function fromEvent(\n target: FromEventTarget,\n eventName: string,\n options?: EventListenerOptions | ((...args: any[]) => T),\n resultSelector?: ((...args: any[]) => T)\n): Observable {\n\n if (isFunction(options)) {\n // DEPRECATED PATH\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n // DEPRECATED PATH\n return fromEvent(target, eventName, options).pipe(\n map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n );\n }\n\n return new Observable(subscriber => {\n function handler(e: T) {\n if (arguments.length > 1) {\n subscriber.next(Array.prototype.slice.call(arguments));\n } else {\n subscriber.next(e);\n }\n }\n setupSubscription(target, eventName, handler, subscriber, options as EventListenerOptions);\n });\n}\n\nfunction setupSubscription(sourceObj: FromEventTarget, eventName: string,\n handler: (...args: any[]) => void, subscriber: Subscriber,\n options?: EventListenerOptions) {\n let unsubscribe: () => void;\n if (isEventTarget(sourceObj)) {\n const source = sourceObj;\n sourceObj.addEventListener(eventName, handler, options);\n unsubscribe = () => source.removeEventListener(eventName, handler, options);\n } else if (isJQueryStyleEventEmitter(sourceObj)) {\n const source = sourceObj;\n sourceObj.on(eventName, handler);\n unsubscribe = () => source.off(eventName, handler);\n } else if (isNodeStyleEventEmitter(sourceObj)) {\n const source = sourceObj;\n sourceObj.addListener(eventName, handler as NodeEventHandler);\n unsubscribe = () => source.removeListener(eventName, handler as NodeEventHandler);\n } else if (sourceObj && (sourceObj as any).length) {\n for (let i = 0, len = (sourceObj as any).length; i < len; i++) {\n setupSubscription(sourceObj[i], eventName, handler, subscriber, options);\n }\n } else {\n throw new TypeError('Invalid event target');\n }\n\n subscriber.add(unsubscribe);\n}\n\nfunction isNodeStyleEventEmitter(sourceObj: any): sourceObj is NodeStyleEventEmitter {\n return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';\n}\n\nfunction isJQueryStyleEventEmitter(sourceObj: any): sourceObj is JQueryStyleEventEmitter {\n return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';\n}\n\nfunction isEventTarget(sourceObj: any): sourceObj is HasEventTargetAddRemove {\n return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { NodeEventHandler } from './fromEvent';\nimport { map } from '../operators/map';\n\n/* tslint:disable:max-line-length */\nexport function fromEventPattern(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void): Observable;\n/** @deprecated resultSelector no longer supported, pipe to map instead */\nexport function fromEventPattern(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void, resultSelector?: (...args: any[]) => T): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable from an arbitrary API for registering event handlers.\n *\n * When that method for adding event handler was something {@link fromEvent}\n * was not prepared for.\n *\n * ![](fromEventPattern.png)\n *\n * `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions\n * for events. It is similar to {@link fromEvent}, but far\n * more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by\n * `fromEventPattern` (although in slightly more verbose way).\n *\n * This operator accepts as a first argument an `addHandler` function, which will be injected with\n * handler parameter. That handler is actually an event handler function that you now can pass\n * to API expecting it. `addHandler` will be called whenever Observable\n * returned by the operator is subscribed, so registering handler in API will not\n * necessarily happen when `fromEventPattern` is called.\n *\n * After registration, every time an event that we listen to happens,\n * Observable returned by `fromEventPattern` will emit value that event handler\n * function was called with. Note that if event handler was called with more\n * then one argument, second and following arguments will not appear in the Observable.\n *\n * If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`\n * another function - `removeHandler` - as a second parameter. It will be injected\n * with the same handler function as before, which now you can use to unregister\n * it from the API. `removeHandler` will be called when consumer of resulting Observable\n * unsubscribes from it.\n *\n * In some APIs unregistering is actually handled differently. Method registering an event handler\n * returns some kind of token, which is later used to identify which function should\n * be unregistered or it itself has method that unregisters event handler.\n * If that is the case with your API, make sure token returned\n * by registering method is returned by `addHandler`. Then it will be passed\n * as a second argument to `removeHandler`, where you will be able to use it.\n *\n * If you need access to all event handler parameters (not only the first one),\n * or you need to transform them in any way, you can call `fromEventPattern` with optional\n * third parameter - project function which will accept all arguments passed to\n * event handler when it is called. Whatever is returned from project function will appear on\n * resulting stream instead of usual event handlers first argument. This means\n * that default project can be thought of as function that takes its first parameter\n * and ignores the rest.\n *\n * ## Example\n * ### Emits clicks happening on the DOM document\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * function addClickHandler(handler) {\n * document.addEventListener('click', handler);\n * }\n *\n * function removeClickHandler(handler) {\n * document.removeEventListener('click', handler);\n * }\n *\n * const clicks = fromEventPattern(\n * addClickHandler,\n * removeClickHandler\n * );\n * clicks.subscribe(x => console.log(x));\n *\n * // Whenever you click anywhere in the browser, DOM MouseEvent\n * // object will be logged.\n * ```\n *\n * ## Example\n * ### Use with API that returns cancellation token\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * const token = someAPI.registerEventHandler(function() {});\n * someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts\n * // not handler itself, but special token.\n *\n * const someAPIObservable = fromEventPattern(\n * function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...\n * function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.\n * );\n * ```\n *\n * ## Example\n * ### Use with project function\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * someAPI.registerEventHandler((eventType, eventMessage) => {\n * console.log(eventType, eventMessage); // Logs \"EVENT_TYPE\" \"EVENT_MESSAGE\" to console.\n * });\n *\n * const someAPIObservable = fromEventPattern(\n * handler => someAPI.registerEventHandler(handler),\n * handler => someAPI.unregisterEventHandler(handler)\n * (eventType, eventMessage) => eventType + \" --- \" + eventMessage // without that function only \"EVENT_TYPE\"\n * ); // would be emitted by the Observable\n *\n * someAPIObservable.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"EVENT_TYPE --- EVENT_MESSAGE\"\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n *\n * @param {function(handler: Function): any} addHandler A function that takes\n * a `handler` function as argument and attaches it somehow to the actual\n * source of events.\n * @param {function(handler: Function, token?: any): void} [removeHandler] A function that\n * takes a `handler` function as an argument and removes it from the event source. If `addHandler`\n * returns some kind of token, `removeHandler` function will have it as a second parameter.\n * @param {function(...args: any): T} [project] A function to\n * transform results. It takes the arguments from the event handler and\n * should return a single value.\n * @return {Observable} Observable which, when an event happens, emits first parameter\n * passed to registered event handler. Alternatively it emits whatever project function returns\n * at that moment.\n * @static true\n * @name fromEventPattern\n * @owner Observable\n */\n\nexport function fromEventPattern(addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n resultSelector?: (...args: any[]) => T): Observable {\n\n if (resultSelector) {\n // DEPRECATED PATH\n return fromEventPattern(addHandler, removeHandler).pipe(\n map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))\n );\n }\n\n return new Observable(subscriber => {\n const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);\n\n let retValue: any;\n try {\n retValue = addHandler(handler);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n\n if (!isFunction(removeHandler)) {\n return undefined;\n }\n\n return () => removeHandler(handler, retValue) ;\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { identity } from '../util/identity';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\n\nexport type ConditionFunc = (state: S) => boolean;\nexport type IterateFunc = (state: S) => S;\nexport type ResultFunc = (state: S) => T;\n\ninterface SchedulerState {\n needIterate?: boolean;\n state: S;\n subscriber: Subscriber;\n condition?: ConditionFunc;\n iterate: IterateFunc;\n resultSelector: ResultFunc;\n}\n\nexport interface GenerateBaseOptions {\n /**\n * Initial state.\n */\n initialState: S;\n /**\n * Condition function that accepts state and returns boolean.\n * When it returns false, the generator stops.\n * If not specified, a generator never stops.\n */\n condition?: ConditionFunc;\n /**\n * Iterate function that accepts state and returns new state.\n */\n iterate: IterateFunc;\n /**\n * SchedulerLike to use for generation process.\n * By default, a generator starts immediately.\n */\n scheduler?: SchedulerLike;\n}\n\nexport interface GenerateOptions extends GenerateBaseOptions {\n /**\n * Result selection function that accepts state and returns a value to emit.\n */\n resultSelector: ResultFunc;\n}\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n *\n * ![](generate.png)\n *\n * @example Produces sequence of 0, 1, 2, ... 9, then completes.\n * const res = generate(0, x => x < 10, x => x + 1, x => x);\n *\n * @example Using asap scheduler, produces sequence of 2, 3, 5, then completes.\n * const res = generate(1, x => x < 5, x => x * 2, x => x + 1, asap);\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {S} initialState Initial state.\n * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).\n * @param {function (state: S): S} iterate Iteration step function.\n * @param {function (state: S): T} resultSelector Selector function for results produced in the sequence. (deprecated)\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} on which to run the generator loop. If not provided, defaults to emit immediately.\n * @returns {Observable} The generated sequence.\n */\n export function generate(initialState: S,\n condition: ConditionFunc,\n iterate: IterateFunc,\n resultSelector: ResultFunc,\n scheduler?: SchedulerLike): Observable;\n\n/**\n * Generates an Observable by running a state-driven loop\n * that emits an element on each iteration.\n *\n * Use it instead of nexting values in a for loop.\n *\n * \n *\n * `generate` allows you to create stream of values generated with a loop very similar to\n * traditional for loop. First argument of `generate` is a beginning value. Second argument\n * is a function that accepts this value and tests if some condition still holds. If it does,\n * loop continues, if not, it stops. Third value is a function which takes previously defined\n * value and modifies it in some way on each iteration. Note how these three parameters\n * are direct equivalents of three expressions in regular for loop: first expression\n * initializes some state (for example numeric index), second tests if loop can make next\n * iteration (for example if index is lower than 10) and third states how defined value\n * will be modified on every step (index will be incremented by one).\n *\n * Return value of a `generate` operator is an Observable that on each loop iteration\n * emits a value. First, condition function is ran. If it returned true, Observable\n * emits currently stored value (initial value at the first iteration) and then updates\n * that value with iterate function. If at some point condition returned false, Observable\n * completes at that moment.\n *\n * Optionally you can pass fourth parameter to `generate` - a result selector function which allows you\n * to immediately map value that would normally be emitted by an Observable.\n *\n * If you find three anonymous functions in `generate` call hard to read, you can provide\n * single object to the operator instead. That object has properties: `initialState`,\n * `condition`, `iterate` and `resultSelector`, which should have respective values that you\n * would normally pass to `generate`. `resultSelector` is still optional, but that form\n * of calling `generate` allows you to omit `condition` as well. If you omit it, that means\n * condition always holds, so output Observable will never complete.\n *\n * Both forms of `generate` can optionally accept a scheduler. In case of multi-parameter call,\n * scheduler simply comes as a last argument (no matter if there is resultSelector\n * function or not). In case of single-parameter call, you can provide it as a\n * `scheduler` property on object passed to the operator. In both cases scheduler decides when\n * next iteration of the loop will happen and therefore when next value will be emitted\n * by the Observable. For example to ensure that each value is pushed to the observer\n * on separate task in event loop, you could use `async` scheduler. Note that\n * by default (when no scheduler is passed) values are simply emitted synchronously.\n *\n *\n * @example Use with condition and iterate functions.\n * const generated = generate(0, x => x < 3, x => x + 1);\n *\n * generated.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // \"Yo!\"\n *\n *\n * @example Use with condition, iterate and resultSelector functions.\n * const generated = generate(0, x => x < 3, x => x + 1, x => x * 1000);\n *\n * generated.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // \"Yo!\"\n *\n *\n * @example Use with options object.\n * const generated = generate({\n * initialState: 0,\n * condition(value) { return value < 3; },\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * generated.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('Yo!')\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // \"Yo!\"\n *\n * @example Use options object without condition function.\n * const generated = generate({\n * initialState: 0,\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * generated.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('Yo!') // This will never run.\n * );\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 3000\n * // ...and never stops.\n *\n *\n * @see {@link from}\n * @see {@link index/Observable.create}\n *\n * @param {S} initialState Initial state.\n * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).\n * @param {function (state: S): S} iterate Iteration step function.\n * @param {function (state: S): T} [resultSelector] Selector function for results produced in the sequence.\n * @param {Scheduler} [scheduler] A {@link Scheduler} on which to run the generator loop. If not provided, defaults to emitting immediately.\n * @return {Observable} The generated sequence.\n */\nexport function generate(initialState: S,\n condition: ConditionFunc,\n iterate: IterateFunc,\n scheduler?: SchedulerLike): Observable;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition and scheduler.\n *\n * ![](generate.png)\n *\n * @example Produces sequence of 0, 1, 2, ... 9, then completes.\n * const res = generate({\n * initialState: 0,\n * condition: x => x < 10,\n * iterate: x => x + 1,\n * });\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {GenerateBaseOptions} options Object that must contain initialState, iterate and might contain condition and scheduler.\n * @returns {Observable} The generated sequence.\n */\nexport function generate(options: GenerateBaseOptions): Observable;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition, result selector and scheduler.\n *\n * ![](generate.png)\n *\n * @example Produces sequence of 0, 1, 2, ... 9, then completes.\n * const res = generate({\n * initialState: 0,\n * condition: x => x < 10,\n * iterate: x => x + 1,\n * resultSelector: x => x,\n * });\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param {GenerateOptions} options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.\n * @returns {Observable} The generated sequence.\n */\nexport function generate(options: GenerateOptions): Observable;\n\nexport function generate(initialStateOrOptions: S | GenerateOptions,\n condition?: ConditionFunc,\n iterate?: IterateFunc,\n resultSelectorOrObservable?: (ResultFunc) | SchedulerLike,\n scheduler?: SchedulerLike): Observable {\n\n let resultSelector: ResultFunc;\n let initialState: S;\n\n if (arguments.length == 1) {\n const options = initialStateOrOptions as GenerateOptions;\n initialState = options.initialState;\n condition = options.condition;\n iterate = options.iterate;\n resultSelector = options.resultSelector || identity as ResultFunc;\n scheduler = options.scheduler;\n } else if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) {\n initialState = initialStateOrOptions as S;\n resultSelector = identity as ResultFunc;\n scheduler = resultSelectorOrObservable as SchedulerLike;\n } else {\n initialState = initialStateOrOptions as S;\n resultSelector = resultSelectorOrObservable as ResultFunc;\n }\n\n return new Observable(subscriber => {\n let state = initialState;\n if (scheduler) {\n return scheduler.schedule>(dispatch, 0, {\n subscriber,\n iterate,\n condition,\n resultSelector,\n state\n });\n }\n\n do {\n if (condition) {\n let conditionResult: boolean;\n try {\n conditionResult = condition(state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n if (!conditionResult) {\n subscriber.complete();\n break;\n }\n }\n let value: T;\n try {\n value = resultSelector(state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n subscriber.next(value);\n if (subscriber.closed) {\n break;\n }\n try {\n state = iterate(state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n } while (true);\n\n return undefined;\n });\n}\n\nfunction dispatch(this: SchedulerAction>, state: SchedulerState) {\n const { subscriber, condition } = state;\n if (subscriber.closed) {\n return undefined;\n }\n if (state.needIterate) {\n try {\n state.state = state.iterate(state.state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n } else {\n state.needIterate = true;\n }\n if (condition) {\n let conditionResult: boolean;\n try {\n conditionResult = condition(state.state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n if (!conditionResult) {\n subscriber.complete();\n return undefined;\n }\n if (subscriber.closed) {\n return undefined;\n }\n }\n let value: T;\n try {\n value = state.resultSelector(state.state);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n if (subscriber.closed) {\n return undefined;\n }\n subscriber.next(value);\n if (subscriber.closed) {\n return undefined;\n }\n return this.schedule(state);\n}\n","import { Observable } from '../Observable';\nimport { defer } from './defer';\nimport { EMPTY } from './empty';\nimport { SubscribableOrPromise } from '../types';\n\n/**\n * Decides at subscription time which Observable will actually be subscribed.\n *\n * `If` statement for Observables.\n *\n * `iif` accepts a condition function and two Observables. When\n * an Observable returned by the operator is subscribed, condition function will be called.\n * Based on what boolean it returns at that moment, consumer will subscribe either to\n * the first Observable (if condition was true) or to the second (if condition was false). Condition\n * function may also not return anything - in that case condition will be evaluated as false and\n * second Observable will be subscribed.\n *\n * Note that Observables for both cases (true and false) are optional. If condition points to an Observable that\n * was left undefined, resulting stream will simply complete immediately. That allows you to, rather\n * then controlling which Observable will be subscribed, decide at runtime if consumer should have access\n * to given Observable or not.\n *\n * If you have more complex logic that requires decision between more than two Observables, {@link defer}\n * will probably be a better choice. Actually `iif` can be easily implemented with {@link defer}\n * and exists only for convenience and readability reasons.\n *\n *\n * ## Examples\n * ### Change at runtime which Observable will be subscribed\n * ```ts\n * import { iif, of } from 'rxjs';\n *\n * let subscribeToFirst;\n * const firstOrSecond = iif(\n * () => subscribeToFirst,\n * of('first'),\n * of('second'),\n * );\n *\n * subscribeToFirst = true;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"first\"\n *\n * subscribeToFirst = false;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // \"second\"\n *\n * ```\n *\n * ### Control an access to an Observable\n * ```ts\n * let accessGranted;\n * const observableIfYouHaveAccess = iif(\n * () => accessGranted,\n * of('It seems you have an access...'), // Note that only one Observable is passed to the operator.\n * );\n *\n * accessGranted = true;\n * observableIfYouHaveAccess.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('The end'),\n * );\n *\n * // Logs:\n * // \"It seems you have an access...\"\n * // \"The end\"\n *\n * accessGranted = false;\n * observableIfYouHaveAccess.subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('The end'),\n * );\n *\n * // Logs:\n * // \"The end\"\n * ```\n *\n * @see {@link defer}\n *\n * @param {function(): boolean} condition Condition which Observable should be chosen.\n * @param {Observable} [trueObservable] An Observable that will be subscribed if condition is true.\n * @param {Observable} [falseObservable] An Observable that will be subscribed if condition is false.\n * @return {Observable} Either first or second Observable, depending on condition.\n * @static true\n * @name iif\n * @owner Observable\n */\nexport function iif(\n condition: () => boolean,\n trueResult: SubscribableOrPromise = EMPTY,\n falseResult: SubscribableOrPromise = EMPTY\n): Observable {\n return defer(() => condition() ? trueResult : falseResult);\n}\n","import { isArray } from './isArray';\n\nexport function isNumeric(val: any): val is number | string {\n // parseFloat NaNs numeric-cast false positives (null|true|false|\"\")\n // ...but misinterprets leading-number strings, particularly hex literals (\"0x...\")\n // subtraction forces infinities to NaN\n // adding 1 corrects loss of precision from parseFloat (#15100)\n return !isArray(val) && (val - parseFloat(val) + 1) >= 0;\n}\n","import { Observable } from '../Observable';\nimport { async } from '../scheduler/async';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { isNumeric } from '../util/isNumeric';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits sequential numbers every specified\n * interval of time, on a specified {@link SchedulerLike}.\n *\n * Emits incremental numbers periodically in time.\n * \n *\n * ![](interval.png)\n *\n * `interval` returns an Observable that emits an infinite sequence of\n * ascending integers, with a constant interval of time of your choosing\n * between those emissions. The first emission is not sent immediately, but\n * only after the first period has passed. By default, this operator uses the\n * `async` {@link SchedulerLike} to provide a notion of time, but you may pass any\n * {@link SchedulerLike} to it.\n *\n * ## Example\n * Emits ascending numbers, one every second (1000ms) up to the number 3\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const numbers = interval(1000);\n *\n * const takeFourNumbers = numbers.pipe(take(4));\n *\n * takeFourNumbers.subscribe(x => console.log('Next: ', x));\n *\n * // Logs:\n * // Next: 0\n * // Next: 1\n * // Next: 2\n * // Next: 3\n * ```\n *\n * @see {@link timer}\n * @see {@link delay}\n *\n * @param {number} [period=0] The interval size in milliseconds (by default)\n * or the time unit determined by the scheduler's clock.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling\n * the emission of values, and providing a notion of \"time\".\n * @return {Observable} An Observable that emits a sequential number each time\n * interval.\n * @static true\n * @name interval\n * @owner Observable\n */\nexport function interval(period = 0,\n scheduler: SchedulerLike = async): Observable {\n if (!isNumeric(period) || period < 0) {\n period = 0;\n }\n\n if (!scheduler || typeof scheduler.schedule !== 'function') {\n scheduler = async;\n }\n\n return new Observable(subscriber => {\n subscriber.add(\n scheduler.schedule(dispatch, period, { subscriber, counter: 0, period })\n );\n return subscriber;\n });\n}\n\nfunction dispatch(this: SchedulerAction, state: IntervalState) {\n const { subscriber, counter, period } = state;\n subscriber.next(counter);\n this.schedule({ subscriber, counter: counter + 1, period }, period);\n}\n\ninterface IntervalState {\n subscriber: Subscriber;\n counter: number;\n period: number;\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike} from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { mergeAll } from '../operators/mergeAll';\nimport { fromArray } from './fromArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, scheduler: SchedulerLike): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, concurrent: number, scheduler: SchedulerLike): Observable;\n\nexport function merge(v1: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, concurrent?: number): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, concurrent?: number): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, concurrent?: number): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, concurrent?: number): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, concurrent?: number): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): Observable;\nexport function merge(v1: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, concurrent?: number): Observable;\nexport function merge(...observables: (ObservableInput | number)[]): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(...observables: (ObservableInput | SchedulerLike | number)[]): Observable;\nexport function merge(...observables: (ObservableInput | number)[]): Observable;\n/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/\nexport function merge(...observables: (ObservableInput | SchedulerLike | number)[]): Observable;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which concurrently emits all values from every\n * given input Observable.\n *\n * Flattens multiple Observables together by blending\n * their values into one Observable.\n *\n * ![](merge.png)\n *\n * `merge` subscribes to each given input Observable (as arguments), and simply\n * forwards (without doing any transformation) all the values from all the input\n * Observables to the output Observable. The output Observable only completes\n * once all input Observables have completed. Any error delivered by an input\n * Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * ### Merge together two Observables: 1s interval and clicks\n * ```ts\n * import { merge, fromEvent, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const clicksOrTimer = merge(clicks, timer);\n * clicksOrTimer.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // timer will emit ascending values, one every second(1000ms) to console\n * // clicks logs MouseEvents to console everytime the \"document\" is clicked\n * // Since the two streams are merged you see these happening\n * // as they occur.\n * ```\n *\n * ### Merge together 3 Observables, but only 2 run concurrently\n * ```ts\n * import { merge, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n * const concurrent = 2; // the argument\n * const merged = merge(timer1, timer2, timer3, concurrent);\n * merged.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - First timer1 and timer2 will run concurrently\n * // - timer1 will emit a value every 1000ms for 10 iterations\n * // - timer2 will emit a value every 2000ms for 6 iterations\n * // - after timer1 hits it's max iteration, timer2 will\n * // continue, and timer3 will start to run concurrently with timer2\n * // - when timer2 hits it's max iteration it terminates, and\n * // timer3 will continue to emit a value every 500ms until it is complete\n * ```\n *\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n *\n * @param {...ObservableInput} observables Input Observables to merge together.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for managing\n * concurrency of input Observables.\n * @return {Observable} an Observable that emits items that are the result of\n * every input Observable.\n * @static true\n * @name merge\n * @owner Observable\n */\nexport function merge(...observables: Array | SchedulerLike | number>): Observable {\n let concurrent = Number.POSITIVE_INFINITY;\n let scheduler: SchedulerLike = null;\n let last: any = observables[observables.length - 1];\n if (isScheduler(last)) {\n scheduler = observables.pop();\n if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {\n concurrent = observables.pop();\n }\n } else if (typeof last === 'number') {\n concurrent = observables.pop();\n }\n\n if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {\n return >observables[0];\n }\n\n return mergeAll(concurrent)(fromArray(observables, scheduler));\n}\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\n\n/**\n * An Observable that emits no items to the Observer and never completes.\n *\n * ![](never.png)\n *\n * A simple Observable that emits neither values nor errors nor the completion\n * notification. It can be used for testing purposes or for composing with other\n * Observables. Please note that by never emitting a complete notification, this\n * Observable keeps the subscription from being disposed automatically.\n * Subscriptions need to be manually disposed.\n *\n * ## Example\n * ### Emit the number 7, then never emit anything else (not even complete)\n * ```ts\n * import { NEVER } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * function info() {\n * console.log('Will not be called');\n * }\n * const result = NEVER.pipe(startWith(7));\n * result.subscribe(x => console.log(x), info, info);\n *\n * ```\n *\n * @see {@link Observable}\n * @see {@link index/EMPTY}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const NEVER = new Observable(noop);\n\n/**\n * @deprecated Deprecated in favor of using {@link NEVER} constant.\n */\nexport function never () {\n return NEVER;\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput } from '../types';\nimport { from } from './from';\nimport { isArray } from '../util/isArray';\nimport { EMPTY } from './empty';\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNext(v: ObservableInput): Observable;\nexport function onErrorResumeNext(v2: ObservableInput, v3: ObservableInput): Observable;\nexport function onErrorResumeNext(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): Observable;\nexport function onErrorResumeNext(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): Observable;\nexport function onErrorResumeNext(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): Observable;\n\nexport function onErrorResumeNext(...observables: Array | ((...values: Array) => R)>): Observable;\nexport function onErrorResumeNext(array: ObservableInput[]): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * Execute series of Observables no matter what, even if it means swallowing errors.\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` Will subscribe to each observable source it is provided, in order.\n * If the source it's subscribed to emits an error or completes, it will move to the next source\n * without error.\n *\n * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link index/EMPTY}.\n *\n * `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its\n * sources emits an error.\n *\n * Note that there is no way to handle any errors thrown by sources via the resuult of\n * `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can\n * always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.\n *\n * ## Example\n * Subscribe to the next Observable after map fails\n * ```ts\n * import { onErrorResumeNext, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * onErrorResumeNext(\n * of(1, 2, 3, 0).pipe(\n * map(x => {\n * if (x === 0) throw Error();\n * return 10 / x;\n * })\n * ),\n * of(1, 2, 3),\n * )\n * .subscribe(\n * val => console.log(val),\n * err => console.log(err), // Will never be called.\n * () => console.log('done'),\n * );\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // \"done\"\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param {...ObservableInput} sources Observables (or anything that *is* observable) passed either directly or as an array.\n * @return {Observable} An Observable that concatenates all sources, one after the other,\n * ignoring all errors, such that any error causes it to move on to the next source.\n */\nexport function onErrorResumeNext(...sources: Array |\n Array> |\n ((...values: Array) => R)>): Observable {\n\n if (sources.length === 0) {\n return EMPTY;\n }\n\n const [ first, ...remainder ] = sources;\n\n if (sources.length === 1 && isArray(first)) {\n return onErrorResumeNext(...first);\n }\n\n return new Observable(subscriber => {\n const subNext = () => subscriber.add(\n onErrorResumeNext(...remainder).subscribe(subscriber)\n );\n\n return from(first).subscribe({\n next(value) { subscriber.next(value); },\n error: subNext,\n complete: subNext,\n });\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\n/**\n * Convert an object into an Observable of `[key, value]` pairs.\n *\n * Turn entries of an object into a stream.\n *\n * \n *\n * `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each\n * emitted array has exactly two elements - the first is a key from the object\n * and the second is a value corresponding to that key. Keys are extracted from\n * an object via `Object.keys` function, which means that they will be only\n * enumerable keys that are present on an object directly - not ones inherited\n * via prototype chain.\n *\n * By default these arrays are emitted synchronously. To change that you can\n * pass a {@link SchedulerLike} as a second argument to `pairs`.\n *\n * @example Converts a javascript object to an Observable\n * ```ts\n * import { pairs } from 'rxjs';\n *\n * const obj = {\n * foo: 42,\n * bar: 56,\n * baz: 78\n * };\n *\n * pairs(obj)\n * .subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('the end!')\n * );\n *\n * // Logs:\n * // [\"foo\", 42],\n * // [\"bar\", 56],\n * // [\"baz\", 78],\n * // \"the end!\"\n * ```\n *\n * @param {Object} obj The object to inspect and turn into an\n * Observable sequence.\n * @param {Scheduler} [scheduler] An optional IScheduler to schedule\n * when resulting Observable will emit values.\n * @returns {(Observable>)} An observable sequence of\n * [key, value] pairs from the object.\n */\nexport function pairs(obj: Object, scheduler?: SchedulerLike): Observable<[string, T]> {\n if (!scheduler) {\n return new Observable<[string, T]>(subscriber => {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length && !subscriber.closed; i++) {\n const key = keys[i];\n if (obj.hasOwnProperty(key)) {\n subscriber.next([key, obj[key]]);\n }\n }\n subscriber.complete();\n });\n } else {\n return new Observable<[string, T]>(subscriber => {\n const keys = Object.keys(obj);\n const subscription = new Subscription();\n subscription.add(\n scheduler.schedule<{ keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }>\n (dispatch, 0, { keys, index: 0, subscriber, subscription, obj }));\n return subscription;\n });\n }\n}\n\n/** @internal */\nexport function dispatch(this: SchedulerAction,\n state: { keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }) {\n const { keys, index, subscriber, subscription, obj } = state;\n if (!subscriber.closed) {\n if (index < keys.length) {\n const key = keys[index];\n subscriber.next([key, obj[key]]);\n subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));\n } else {\n subscriber.complete();\n }\n }\n}\n","export function not(pred: Function, thisArg: any): Function {\n function notPred(): any {\n return !(( notPred).pred.apply(( notPred).thisArg, arguments));\n }\n ( notPred).pred = pred;\n ( notPred).thisArg = thisArg;\n return notPred;\n}","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function filter(predicate: (value: T, index: number) => value is S,\n thisArg?: any): OperatorFunction;\nexport function filter(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.\n *\n * ![](filter.png)\n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n * Emit only click events whose target was a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { filter } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of values from the source that were\n * allowed by the `predicate` function.\n * @method filter\n * @owner Observable\n */\nexport function filter(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction {\n return function filterOperatorFunction(source: Observable): Observable {\n return source.lift(new FilterOperator(predicate, thisArg));\n };\n}\n\nclass FilterOperator implements Operator {\n constructor(private predicate: (value: T, index: number) => boolean,\n private thisArg?: any) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FilterSubscriber extends Subscriber {\n\n count: number = 0;\n\n constructor(destination: Subscriber,\n private predicate: (value: T, index: number) => boolean,\n private thisArg: any) {\n super(destination);\n }\n\n // the try catch block below is left specifically for\n // optimization and perf reasons. a tryCatcher is not necessary here.\n protected _next(value: T) {\n let result: any;\n try {\n result = this.predicate.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n if (result) {\n this.destination.next(value);\n }\n }\n}\n","import { not } from '../util/not';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { filter } from '../operators/filter';\nimport { ObservableInput } from '../types';\nimport { Observable } from '../Observable';\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.\n *\n * ![](partition.png)\n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n * Partition a set of numbers into odds and evens observables\n * ```ts\n * import { of, partition } from 'rxjs';\n *\n * const observableValues = of(1, 2, 3, 4, 5, 6);\n * const [evens$, odds$] = partition(observableValues, (value, index) => value % 2 === 0);\n *\n * odds$.subscribe(x => console.log('odds', x));\n * evens$.subscribe(x => console.log('evens', x));\n *\n * // Logs:\n * // odds 1\n * // odds 3\n * // odds 5\n * // evens 2\n * // evens 4\n * // evens 6\n * ```\n *\n * @see {@link filter}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted on the first Observable in the returned array, if\n * `false` the value is emitted on the second Observable in the array. The\n * `index` parameter is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {[Observable, Observable]} An array with two Observables: one\n * with values that passed the predicate, and another with values that did not\n * pass the predicate.\n */\nexport function partition(\n source: ObservableInput,\n predicate: (value: T, index: number) => boolean,\n thisArg?: any\n): [Observable, Observable] {\n return [\n filter(predicate, thisArg)(new Observable(subscribeTo(source))),\n filter(not(predicate, thisArg) as any)(new Observable(subscribeTo(source)))\n ] as [Observable, Observable];\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { fromArray } from './fromArray';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { TeardownLogic, ObservableInput } from '../types';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\n// tslint:disable:max-line-length\nexport function race(arg: [ObservableInput]): Observable;\nexport function race(arg: [ObservableInput, ObservableInput]): Observable;\nexport function race(arg: [ObservableInput, ObservableInput, ObservableInput]): Observable;\nexport function race(arg: [ObservableInput, ObservableInput, ObservableInput, ObservableInput]): Observable;\nexport function race(arg: [ObservableInput, ObservableInput, ObservableInput, ObservableInput, ObservableInput]): Observable;\nexport function race(arg: ObservableInput[]): Observable;\nexport function race(arg: ObservableInput[]): Observable<{}>;\n\nexport function race(a: ObservableInput): Observable;\nexport function race(a: ObservableInput, b: ObservableInput): Observable;\nexport function race(a: ObservableInput, b: ObservableInput, c: ObservableInput): Observable;\nexport function race(a: ObservableInput, b: ObservableInput, c: ObservableInput, d: ObservableInput): Observable;\nexport function race(a: ObservableInput, b: ObservableInput, c: ObservableInput, d: ObservableInput, e: ObservableInput): Observable;\n// tslint:enable:max-line-length\n\nexport function race(observables: ObservableInput[]): Observable;\nexport function race(observables: ObservableInput[]): Observable<{}>;\nexport function race(...observables: ObservableInput[]): Observable;\nexport function race(...observables: ObservableInput[]): Observable<{}>;\n\n/**\n * Returns an Observable that mirrors the first source Observable to emit an item.\n *\n * ## Example\n * ### Subscribes to the observable that was the first to start emitting.\n *\n * ```ts\n * import { race, interval } from 'rxjs';\n * import { mapTo } from 'rxjs/operators';\n *\n * const obs1 = interval(1000).pipe(mapTo('fast one'));\n * const obs2 = interval(3000).pipe(mapTo('medium one'));\n * const obs3 = interval(5000).pipe(mapTo('slow one'));\n *\n * race(obs3, obs1, obs2)\n * .subscribe(\n * winner => console.log(winner)\n * );\n *\n * // result:\n * // a series of 'fast one'\n * ```\n *\n * @param {...Observables} ...observables sources used to race for which Observable emits first.\n * @return {Observable} an Observable that mirrors the output of the first Observable to emit an item.\n * @static true\n * @name race\n * @owner Observable\n */\nexport function race(...observables: ObservableInput[]): Observable {\n // if the only argument is an array, it was most likely called with\n // `race([obs1, obs2, ...])`\n if (observables.length === 1) {\n if (isArray(observables[0])) {\n observables = observables[0] as Observable[];\n } else {\n return observables[0] as Observable;\n }\n }\n\n return fromArray(observables, undefined).lift(new RaceOperator());\n}\n\nexport class RaceOperator implements Operator {\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new RaceSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class RaceSubscriber extends OuterSubscriber {\n private hasFirst: boolean = false;\n private observables: Observable[] = [];\n private subscriptions: Subscription[] = [];\n\n constructor(destination: Subscriber) {\n super(destination);\n }\n\n protected _next(observable: any): void {\n this.observables.push(observable);\n }\n\n protected _complete() {\n const observables = this.observables;\n const len = observables.length;\n\n if (len === 0) {\n this.destination.complete();\n } else {\n for (let i = 0; i < len && !this.hasFirst; i++) {\n let observable = observables[i];\n let subscription = subscribeToResult(this, observable, observable as any, i);\n\n if (this.subscriptions) {\n this.subscriptions.push(subscription);\n }\n this.add(subscription);\n }\n this.observables = null;\n }\n }\n\n notifyNext(outerValue: T, innerValue: T,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n if (!this.hasFirst) {\n this.hasFirst = true;\n\n for (let i = 0; i < this.subscriptions.length; i++) {\n if (i !== outerIndex) {\n let subscription = this.subscriptions[i];\n\n subscription.unsubscribe();\n this.remove(subscription);\n }\n }\n\n this.subscriptions = null;\n }\n\n this.destination.next(innerValue);\n }\n}\n","import { SchedulerAction, SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\n\n/**\n * Creates an Observable that emits a sequence of numbers within a specified\n * range.\n *\n * Emits a sequence of numbers in a range.\n *\n * ![](range.png)\n *\n * `range` operator emits a range of sequential integers, in order, where you\n * select the `start` of the range and its `length`. By default, uses no\n * {@link SchedulerLike} and just delivers the notifications synchronously, but may use\n * an optional {@link SchedulerLike} to regulate those deliveries.\n *\n * ## Example\n * Emits the numbers 1 to 10\n * ```ts\n * import { range } from 'rxjs';\n *\n * const numbers = range(1, 10);\n * numbers.subscribe(x => console.log(x));\n * ```\n * @see {@link timer}\n * @see {@link index/interval}\n *\n * @param {number} [start=0] The value of the first integer in the sequence.\n * @param {number} count The number of sequential integers to generate.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emissions of the notifications.\n * @return {Observable} An Observable of numbers that emits a finite range of\n * sequential integers.\n * @static true\n * @name range\n * @owner Observable\n */\nexport function range(start: number = 0,\n count?: number,\n scheduler?: SchedulerLike): Observable {\n return new Observable(subscriber => {\n if (count === undefined) {\n count = start;\n start = 0;\n }\n\n let index = 0;\n let current = start;\n\n if (scheduler) {\n return scheduler.schedule(dispatch, 0, {\n index, count, start, subscriber\n });\n } else {\n do {\n if (index++ >= count) {\n subscriber.complete();\n break;\n }\n subscriber.next(current++);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n }\n\n return undefined;\n });\n}\n\n/** @internal */\nexport function dispatch(this: SchedulerAction, state: any) {\n const { start, index, count, subscriber } = state;\n\n if (index >= count) {\n subscriber.complete();\n return;\n }\n\n subscriber.next(start);\n\n if (subscriber.closed) {\n return;\n }\n\n state.index = index + 1;\n state.start = start + 1;\n\n this.schedule(state);\n}\n","import { Observable } from '../Observable';\nimport { SchedulerAction, SchedulerLike } from '../types';\nimport { async } from '../scheduler/async';\nimport { isNumeric } from '../util/isNumeric';\nimport { isScheduler } from '../util/isScheduler';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that starts emitting after an `dueTime` and\n * emits ever increasing numbers after each `period` of time thereafter.\n *\n * Its like {@link index/interval}, but you can specify when\n * should the emissions start.\n *\n * ![](timer.png)\n *\n * `timer` returns an Observable that emits an infinite sequence of ascending\n * integers, with a constant interval of time, `period` of your choosing\n * between those emissions. The first emission happens after the specified\n * `dueTime`. The initial delay may be a `Date`. By default, this\n * operator uses the {@link asyncScheduler} {@link SchedulerLike} to provide a notion of time, but you\n * may pass any {@link SchedulerLike} to it. If `period` is not specified, the output\n * Observable emits only one value, `0`. Otherwise, it emits an infinite\n * sequence.\n *\n * ## Examples\n * ### Emits ascending numbers, one every second (1000ms), starting after 3 seconds\n * ```ts\n * import { timer } from 'rxjs';\n *\n * const numbers = timer(3000, 1000);\n * numbers.subscribe(x => console.log(x));\n * ```\n *\n * ### Emits one number after five seconds\n * ```ts\n * import { timer } from 'rxjs';\n *\n * const numbers = timer(5000);\n * numbers.subscribe(x => console.log(x));\n * ```\n * @see {@link index/interval}\n * @see {@link delay}\n *\n * @param {number|Date} [dueTime] The initial delay time specified as a Date object or as an integer denoting\n * milliseconds to wait before emitting the first value of 0`.\n * @param {number|SchedulerLike} [periodOrScheduler] The period of time between emissions of the\n * subsequent numbers.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling\n * the emission of values, and providing a notion of \"time\".\n * @return {Observable} An Observable that emits a `0` after the\n * `dueTime` and ever increasing numbers after each `period` of time\n * thereafter.\n * @static true\n * @name timer\n * @owner Observable\n */\nexport function timer(dueTime: number | Date = 0,\n periodOrScheduler?: number | SchedulerLike,\n scheduler?: SchedulerLike): Observable {\n let period = -1;\n if (isNumeric(periodOrScheduler)) {\n period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);\n } else if (isScheduler(periodOrScheduler)) {\n scheduler = periodOrScheduler as any;\n }\n\n if (!isScheduler(scheduler)) {\n scheduler = async;\n }\n\n return new Observable(subscriber => {\n const due = isNumeric(dueTime)\n ? (dueTime as number)\n : (+dueTime - scheduler.now());\n\n return scheduler.schedule(dispatch, due, {\n index: 0, period, subscriber\n });\n });\n}\n\ninterface TimerState {\n index: number;\n period: number;\n subscriber: Subscriber;\n}\n\nfunction dispatch(this: SchedulerAction, state: TimerState) {\n const { index, period, subscriber } = state;\n subscriber.next(index);\n\n if (subscriber.closed) {\n return;\n } else if (period === -1) {\n return subscriber.complete();\n }\n\n state.index = index + 1;\n this.schedule(state, period);\n}\n","import { Observable } from '../Observable';\nimport { Unsubscribable, ObservableInput } from '../types';\nimport { from } from './from'; // from from from! LAWL\nimport { EMPTY } from './empty';\n\n/**\n * Creates an Observable that uses a resource which will be disposed at the same time as the Observable.\n *\n * Use it when you catch yourself cleaning up after an Observable.\n *\n * `using` is a factory operator, which accepts two functions. First function returns a disposable resource.\n * It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with\n * that object and should return an Observable. That Observable can use resource object during its execution.\n * Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor\n * resource object will be shared in any way between subscriptions.\n *\n * When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed\n * as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output\n * Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,\n * the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which\n * otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone\n * cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make\n * sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.\n *\n * @see {@link defer}\n *\n * @param {function(): ISubscription} resourceFactory A function which creates any resource object\n * that implements `unsubscribe` method.\n * @param {function(resource: ISubscription): Observable} observableFactory A function which\n * creates an Observable, that can use injected resource object.\n * @return {Observable} An Observable that behaves the same as Observable returned by `observableFactory`, but\n * which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.\n */\nexport function using(resourceFactory: () => Unsubscribable | void,\n observableFactory: (resource: Unsubscribable | void) => ObservableInput | void): Observable {\n return new Observable(subscriber => {\n let resource: Unsubscribable | void;\n\n try {\n resource = resourceFactory();\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n\n let result: ObservableInput | void;\n try {\n result = observableFactory(resource);\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n\n const source = result ? from(result) : EMPTY;\n const subscription = source.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n if (resource) {\n resource.unsubscribe();\n }\n };\n });\n}\n","import { Observable } from '../Observable';\nimport { fromArray } from './fromArray';\nimport { isArray } from '../util/isArray';\nimport { Operator } from '../Operator';\nimport { ObservableInput, PartialObserver, ObservedValueOf } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { iterator as Symbol_iterator } from '../../internal/symbol/iterator';\n\n/* tslint:disable:max-line-length */\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, R>(v1: O1, resultSelector: (v1: ObservedValueOf) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, O2 extends ObservableInput, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf, v6: ObservedValueOf) => R): Observable;\n\nexport function zip, O2 extends ObservableInput>(v1: O1, v2: O2): Observable<[ObservedValueOf, ObservedValueOf]>;\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput>(v1: O1, v2: O2, v3: O3): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function zip, O2 extends ObservableInput, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<[ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\n\nexport function zip>(array: O[]): Observable[]>;\nexport function zip(array: ObservableInput[]): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip, R>(array: O[], resultSelector: (...values: ObservedValueOf[]) => R): Observable;\n/** @deprecated resultSelector is no longer supported, pipe to map instead */\nexport function zip(array: ObservableInput[], resultSelector: (...values: any[]) => R): Observable;\n\nexport function zip>(...observables: O[]): Observable[]>;\nexport function zip, R>(...observables: Array[]) => R)>): Observable;\nexport function zip(...observables: Array | ((...values: Array) => R)>): Observable;\n/* tslint:enable:max-line-length */\n\n/**\n * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each\n * of its input Observables.\n *\n * If the last parameter is a function, this function is used to compute the created value from the input values.\n * Otherwise, an array of the input values is returned.\n *\n * ## Example\n * Combine age and name from different sources\n * ```ts\n * import { zip, of } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * let age$ = of(27, 25, 29);\n * let name$ = of('Foo', 'Bar', 'Beer');\n * let isDev$ = of(true, true, false);\n *\n * zip(age$, name$, isDev$).pipe(\n * map(([age, name, isDev]) => ({ age, name, isDev })),\n * )\n * .subscribe(x => console.log(x));\n *\n * // outputs\n * // { age: 27, name: 'Foo', isDev: true }\n * // { age: 25, name: 'Bar', isDev: true }\n * // { age: 29, name: 'Beer', isDev: false }\n * ```\n * @param observables\n * @return {Observable}\n * @static true\n * @name zip\n * @owner Observable\n */\nexport function zip, R>(\n ...observables: Array[]) => R)>\n): Observable[]|R> {\n const resultSelector = <((...ys: Array) => R)> observables[observables.length - 1];\n if (typeof resultSelector === 'function') {\n observables.pop();\n }\n return fromArray(observables, undefined).lift(new ZipOperator(resultSelector));\n}\n\nexport class ZipOperator implements Operator {\n\n resultSelector: (...values: Array) => R;\n\n constructor(resultSelector?: (...values: Array) => R) {\n this.resultSelector = resultSelector;\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ZipSubscriber extends Subscriber {\n private values: any;\n private resultSelector: (...values: Array) => R;\n private iterators: LookAheadIterator[] = [];\n private active = 0;\n\n constructor(destination: Subscriber,\n resultSelector?: (...values: Array) => R,\n values: any = Object.create(null)) {\n super(destination);\n this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;\n this.values = values;\n }\n\n protected _next(value: any) {\n const iterators = this.iterators;\n if (isArray(value)) {\n iterators.push(new StaticArrayIterator(value));\n } else if (typeof value[Symbol_iterator] === 'function') {\n iterators.push(new StaticIterator(value[Symbol_iterator]()));\n } else {\n iterators.push(new ZipBufferIterator(this.destination, this, value));\n }\n }\n\n protected _complete() {\n const iterators = this.iterators;\n const len = iterators.length;\n\n this.unsubscribe();\n\n if (len === 0) {\n this.destination.complete();\n return;\n }\n\n this.active = len;\n for (let i = 0; i < len; i++) {\n let iterator: ZipBufferIterator = iterators[i];\n if (iterator.stillUnsubscribed) {\n const destination = this.destination as Subscription;\n destination.add(iterator.subscribe(iterator, i));\n } else {\n this.active--; // not an observable\n }\n }\n }\n\n notifyInactive() {\n this.active--;\n if (this.active === 0) {\n this.destination.complete();\n }\n }\n\n checkIterators() {\n const iterators = this.iterators;\n const len = iterators.length;\n const destination = this.destination;\n\n // abort if not all of them have values\n for (let i = 0; i < len; i++) {\n let iterator = iterators[i];\n if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {\n return;\n }\n }\n\n let shouldComplete = false;\n const args: any[] = [];\n for (let i = 0; i < len; i++) {\n let iterator = iterators[i];\n let result = iterator.next();\n\n // check to see if it's completed now that you've gotten\n // the next value.\n if (iterator.hasCompleted()) {\n shouldComplete = true;\n }\n\n if (result.done) {\n destination.complete();\n return;\n }\n\n args.push(result.value);\n }\n\n if (this.resultSelector) {\n this._tryresultSelector(args);\n } else {\n destination.next(args);\n }\n\n if (shouldComplete) {\n destination.complete();\n }\n }\n\n protected _tryresultSelector(args: any[]) {\n let result: any;\n try {\n result = this.resultSelector.apply(this, args);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n\ninterface LookAheadIterator extends Iterator {\n hasValue(): boolean;\n hasCompleted(): boolean;\n}\n\nclass StaticIterator implements LookAheadIterator {\n private nextResult: IteratorResult;\n\n constructor(private iterator: Iterator) {\n this.nextResult = iterator.next();\n }\n\n hasValue() {\n return true;\n }\n\n next(): IteratorResult {\n const result = this.nextResult;\n this.nextResult = this.iterator.next();\n return result;\n }\n\n hasCompleted() {\n const nextResult = this.nextResult;\n return nextResult && nextResult.done;\n }\n}\n\nclass StaticArrayIterator implements LookAheadIterator {\n private index = 0;\n private length = 0;\n\n constructor(private array: T[]) {\n this.length = array.length;\n }\n\n [Symbol_iterator]() {\n return this;\n }\n\n next(value?: any): IteratorResult {\n const i = this.index++;\n const array = this.array;\n return i < this.length ? { value: array[i], done: false } : { value: null, done: true };\n }\n\n hasValue() {\n return this.array.length > this.index;\n }\n\n hasCompleted() {\n return this.array.length === this.index;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ZipBufferIterator extends OuterSubscriber implements LookAheadIterator {\n stillUnsubscribed = true;\n buffer: T[] = [];\n isComplete = false;\n\n constructor(destination: PartialObserver,\n private parent: ZipSubscriber,\n private observable: Observable) {\n super(destination);\n }\n\n [Symbol_iterator]() {\n return this;\n }\n\n // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next\n // this is legit because `next()` will never be called by a subscription in this case.\n next(): IteratorResult {\n const buffer = this.buffer;\n if (buffer.length === 0 && this.isComplete) {\n return { value: null, done: true };\n } else {\n return { value: buffer.shift(), done: false };\n }\n }\n\n hasValue() {\n return this.buffer.length > 0;\n }\n\n hasCompleted() {\n return this.buffer.length === 0 && this.isComplete;\n }\n\n notifyComplete() {\n if (this.buffer.length > 0) {\n this.isComplete = true;\n this.parent.notifyInactive();\n } else {\n this.destination.complete();\n }\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.buffer.push(innerValue);\n this.parent.checkIterators();\n }\n\n subscribe(value: any, index: number) {\n return subscribeToResult(this, this.observable, this, index);\n }\n}\n","/* Observable */\nexport { Observable } from './internal/Observable';\nexport { ConnectableObservable } from './internal/observable/ConnectableObservable';\nexport { GroupedObservable } from './internal/operators/groupBy';\nexport { Operator } from './internal/Operator';\nexport { observable } from './internal/symbol/observable';\n\n/* Subjects */\nexport { Subject } from './internal/Subject';\nexport { BehaviorSubject } from './internal/BehaviorSubject';\nexport { ReplaySubject } from './internal/ReplaySubject';\nexport { AsyncSubject } from './internal/AsyncSubject';\n\n/* Schedulers */\nexport { asap as asapScheduler } from './internal/scheduler/asap';\nexport { async as asyncScheduler } from './internal/scheduler/async';\nexport { queue as queueScheduler } from './internal/scheduler/queue';\nexport { animationFrame as animationFrameScheduler } from './internal/scheduler/animationFrame';\nexport { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/VirtualTimeScheduler';\nexport { Scheduler } from './internal/Scheduler';\n\n/* Subscription */\nexport { Subscription } from './internal/Subscription';\nexport { Subscriber } from './internal/Subscriber';\n\n/* Notification */\nexport { Notification, NotificationKind } from './internal/Notification';\n\n/* Utils */\nexport { pipe } from './internal/util/pipe';\nexport { noop } from './internal/util/noop';\nexport { identity } from './internal/util/identity';\nexport { isObservable } from './internal/util/isObservable';\n\n/* Error types */\nexport { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';\nexport { EmptyError } from './internal/util/EmptyError';\nexport { ObjectUnsubscribedError } from './internal/util/ObjectUnsubscribedError';\nexport { UnsubscriptionError } from './internal/util/UnsubscriptionError';\nexport { TimeoutError } from './internal/util/TimeoutError';\n\n/* Static observable creation exports */\nexport { bindCallback } from './internal/observable/bindCallback';\nexport { bindNodeCallback } from './internal/observable/bindNodeCallback';\nexport { combineLatest } from './internal/observable/combineLatest';\nexport { concat } from './internal/observable/concat';\nexport { defer } from './internal/observable/defer';\nexport { empty } from './internal/observable/empty';\nexport { forkJoin } from './internal/observable/forkJoin';\nexport { from } from './internal/observable/from';\nexport { fromEvent } from './internal/observable/fromEvent';\nexport { fromEventPattern } from './internal/observable/fromEventPattern';\nexport { generate } from './internal/observable/generate';\nexport { iif } from './internal/observable/iif';\nexport { interval } from './internal/observable/interval';\nexport { merge } from './internal/observable/merge';\nexport { never } from './internal/observable/never';\nexport { of } from './internal/observable/of';\nexport { onErrorResumeNext } from './internal/observable/onErrorResumeNext';\nexport { pairs } from './internal/observable/pairs';\nexport { partition } from './internal/observable/partition';\nexport { race } from './internal/observable/race';\nexport { range } from './internal/observable/range';\nexport { throwError } from './internal/observable/throwError';\nexport { timer } from './internal/observable/timer';\nexport { using } from './internal/observable/using';\nexport { zip } from './internal/observable/zip';\nexport { scheduled } from './internal/scheduled/scheduled';\n\n/* Constants */\nexport { EMPTY } from './internal/observable/empty';\nexport { NEVER } from './internal/observable/never';\n\n/* Types */\nexport * from './internal/types';\n\n/* Config */\nexport { config } from './internal/config';\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\n/**\n * Ignores source values for a duration determined by another Observable, then\n * emits the most recent value from the source Observable, then repeats this\n * process.\n *\n * It's like {@link auditTime}, but the silencing\n * duration is determined by a second Observable.\n *\n * ![](audit.png)\n *\n * `audit` is similar to `throttle`, but emits the last value from the silenced\n * time window, instead of the first value. `audit` emits the most recent value\n * from the source Observable on the output Observable as soon as its internal\n * timer becomes disabled, and ignores source values while the timer is enabled.\n * Initially, the timer is disabled. As soon as the first source value arrives,\n * the timer is enabled by calling the `durationSelector` function with the\n * source value, which returns the \"duration\" Observable. When the duration\n * Observable emits a value or completes, the timer is disabled, then the most\n * recent source value is emitted on the output Observable, and this process\n * repeats for the next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { audit } from 'rxjs/operators'\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(audit(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttle}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration, returned as an Observable or a Promise.\n * @return {Observable} An Observable that performs rate-limiting of\n * emissions from the source Observable.\n * @method audit\n * @owner Observable\n */\nexport function audit(durationSelector: (value: T) => SubscribableOrPromise): MonoTypeOperatorFunction {\n return function auditOperatorFunction(source: Observable) {\n return source.lift(new AuditOperator(durationSelector));\n };\n}\n\nclass AuditOperator implements Operator {\n constructor(private durationSelector: (value: T) => SubscribableOrPromise) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass AuditSubscriber extends OuterSubscriber {\n\n private value: T;\n private hasValue: boolean = false;\n private throttled: Subscription;\n\n constructor(destination: Subscriber,\n private durationSelector: (value: T) => SubscribableOrPromise) {\n super(destination);\n }\n\n protected _next(value: T): void {\n this.value = value;\n this.hasValue = true;\n if (!this.throttled) {\n let duration;\n try {\n const { durationSelector } = this;\n duration = durationSelector(value);\n } catch (err) {\n return this.destination.error(err);\n }\n const innerSubscription = subscribeToResult(this, duration);\n if (!innerSubscription || innerSubscription.closed) {\n this.clearThrottle();\n } else {\n this.add(this.throttled = innerSubscription);\n }\n }\n }\n\n clearThrottle() {\n const { value, hasValue, throttled } = this;\n if (throttled) {\n this.remove(throttled);\n this.throttled = null;\n throttled.unsubscribe();\n }\n if (hasValue) {\n this.value = null;\n this.hasValue = false;\n this.destination.next(value);\n }\n }\n\n notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {\n this.clearThrottle();\n }\n\n notifyComplete(): void {\n this.clearThrottle();\n }\n}\n","import { async } from '../scheduler/async';\nimport { audit } from './audit';\nimport { timer } from '../observable/timer';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/**\n * Ignores source values for `duration` milliseconds, then emits the most recent\n * value from the source Observable, then repeats this process.\n *\n * When it sees a source value, it ignores that plus\n * the next ones for `duration` milliseconds, and then it emits the most recent\n * value from the source.\n *\n * ![](auditTime.png)\n *\n * `auditTime` is similar to `throttleTime`, but emits the last value from the\n * silenced time window, instead of the first value. `auditTime` emits the most\n * recent value from the source Observable on the output Observable as soon as\n * its internal timer becomes disabled, and ignores source values while the\n * timer is enabled. Initially, the timer is disabled. As soon as the first\n * source value arrives, the timer is enabled. After `duration` milliseconds (or\n * the time unit determined internally by the optional `scheduler`) has passed,\n * the timer is disabled, then the most recent source value is emitted on the\n * output Observable, and this process repeats for the next source value.\n * Optionally takes a {@link SchedulerLike} for managing timers.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { auditTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(auditTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} duration Time to wait before emitting the most recent source\n * value, measured in milliseconds or the time unit determined internally\n * by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the rate-limiting behavior.\n * @return {Observable} An Observable that performs rate-limiting of\n * emissions from the source Observable.\n * @method auditTime\n * @owner Observable\n */\nexport function auditTime(duration: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction {\n return audit(() => timer(duration, scheduler));\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Buffers the source Observable values until `closingNotifier` emits.\n *\n * Collects values from the past as an array, and emits\n * that array only when another Observable emits.\n *\n * ![](content/img/buffer.png)\n *\n * Buffers the incoming Observable values until the given `closingNotifier`\n * Observable emits a value, at which point it emits the buffer on the output\n * Observable and starts a new buffer internally, awaiting the next time\n * `closingNotifier` emits.\n *\n * ## Example\n *\n * On every click, emit array of most recent interval events\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { buffer } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const intervalEvents = interval(1000);\n * const buffered = intervalEvents.pipe(buffer(clicks));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link window}\n *\n * @param {Observable} closingNotifier An Observable that signals the\n * buffer to be emitted on the output Observable.\n * @return {Observable} An Observable of buffers, which are arrays of\n * values.\n * @method buffer\n * @owner Observable\n */\nexport function buffer(closingNotifier: Observable): OperatorFunction {\n return function bufferOperatorFunction(source: Observable) {\n return source.lift(new BufferOperator(closingNotifier));\n };\n}\n\nclass BufferOperator implements Operator {\n\n constructor(private closingNotifier: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferSubscriber extends OuterSubscriber {\n private buffer: T[] = [];\n\n constructor(destination: Subscriber, closingNotifier: Observable) {\n super(destination);\n this.add(subscribeToResult(this, closingNotifier));\n }\n\n protected _next(value: T) {\n this.buffer.push(value);\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n const buffer = this.buffer;\n this.buffer = [];\n this.destination.next(buffer);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Buffers the source Observable values until the size hits the maximum\n * `bufferSize` given.\n *\n * Collects values from the past as an array, and emits\n * that array only when its size reaches `bufferSize`.\n *\n * ![](bufferCount.png)\n *\n * Buffers a number of values from the source Observable by `bufferSize` then\n * emits the buffer and clears it, and starts a new buffer each\n * `startBufferEvery` values. If `startBufferEvery` is not provided or is\n * `null`, then new buffers are started immediately at the start of the source\n * and when each buffer closes and is emitted.\n *\n * ## Examples\n *\n * Emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferCount } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * On every click, emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferCount } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2, 1));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link pairwise}\n * @see {@link windowCount}\n *\n * @param {number} bufferSize The maximum size of the buffer emitted.\n * @param {number} [startBufferEvery] Interval at which to start a new buffer.\n * For example if `startBufferEvery` is `2`, then a new buffer will be started\n * on every other value from the source. A new buffer is started at the\n * beginning of the source by default.\n * @return {Observable} An Observable of arrays of buffered values.\n * @method bufferCount\n * @owner Observable\n */\nexport function bufferCount(bufferSize: number, startBufferEvery: number = null): OperatorFunction {\n return function bufferCountOperatorFunction(source: Observable) {\n return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));\n };\n}\n\nclass BufferCountOperator implements Operator {\n private subscriberClass: any;\n\n constructor(private bufferSize: number, private startBufferEvery: number) {\n if (!startBufferEvery || bufferSize === startBufferEvery) {\n this.subscriberClass = BufferCountSubscriber;\n } else {\n this.subscriberClass = BufferSkipCountSubscriber;\n }\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferCountSubscriber extends Subscriber {\n private buffer: T[] = [];\n\n constructor(destination: Subscriber, private bufferSize: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const buffer = this.buffer;\n\n buffer.push(value);\n\n if (buffer.length == this.bufferSize) {\n this.destination.next(buffer);\n this.buffer = [];\n }\n }\n\n protected _complete(): void {\n const buffer = this.buffer;\n if (buffer.length > 0) {\n this.destination.next(buffer);\n }\n super._complete();\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferSkipCountSubscriber extends Subscriber {\n private buffers: Array = [];\n private count: number = 0;\n\n constructor(destination: Subscriber, private bufferSize: number, private startBufferEvery: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const { bufferSize, startBufferEvery, buffers, count } = this;\n\n this.count++;\n if (count % startBufferEvery === 0) {\n buffers.push([]);\n }\n\n for (let i = buffers.length; i--; ) {\n const buffer = buffers[i];\n buffer.push(value);\n if (buffer.length === bufferSize) {\n buffers.splice(i, 1);\n this.destination.next(buffer);\n }\n }\n }\n\n protected _complete(): void {\n const { buffers, destination } = this;\n\n while (buffers.length > 0) {\n let buffer = buffers.shift();\n if (buffer.length > 0) {\n destination.next(buffer);\n }\n }\n super._complete();\n }\n\n}\n","import { Operator } from '../Operator';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { isScheduler } from '../util/isScheduler';\nimport { OperatorFunction, SchedulerAction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function bufferTime(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction;\nexport function bufferTime(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, scheduler?: SchedulerLike): OperatorFunction;\nexport function bufferTime(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, maxBufferSize: number, scheduler?: SchedulerLike): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Buffers the source Observable values for a specific time period.\n *\n * Collects values from the past as an array, and emits\n * those arrays periodically in time.\n *\n * ![](bufferTime.png)\n *\n * Buffers values from the source for a specific time duration `bufferTimeSpan`.\n * Unless the optional argument `bufferCreationInterval` is given, it emits and\n * resets the buffer every `bufferTimeSpan` milliseconds. If\n * `bufferCreationInterval` is given, this operator opens the buffer every\n * `bufferCreationInterval` milliseconds and closes (emits and resets) the\n * buffer every `bufferTimeSpan` milliseconds. When the optional argument\n * `maxBufferSize` is specified, the buffer will be closed either after\n * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.\n *\n * ## Examples\n *\n * Every second, emit an array of the recent click events\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(1000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds, emit the click events from the next 2 seconds\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { bufferTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(2000, 5000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link windowTime}\n *\n * @param {number} bufferTimeSpan The amount of time to fill each buffer array.\n * @param {number} [bufferCreationInterval] The interval at which to start new\n * buffers.\n * @param {number} [maxBufferSize] The maximum buffer size.\n * @param {SchedulerLike} [scheduler=async] The scheduler on which to schedule the\n * intervals that determine buffer boundaries.\n * @return {Observable} An observable of arrays of buffered values.\n * @method bufferTime\n * @owner Observable\n */\nexport function bufferTime(bufferTimeSpan: number): OperatorFunction {\n let length: number = arguments.length;\n\n let scheduler: SchedulerLike = async;\n if (isScheduler(arguments[arguments.length - 1])) {\n scheduler = arguments[arguments.length - 1];\n length--;\n }\n\n let bufferCreationInterval: number = null;\n if (length >= 2) {\n bufferCreationInterval = arguments[1];\n }\n\n let maxBufferSize: number = Number.POSITIVE_INFINITY;\n if (length >= 3) {\n maxBufferSize = arguments[2];\n }\n\n return function bufferTimeOperatorFunction(source: Observable) {\n return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));\n };\n}\n\nclass BufferTimeOperator implements Operator {\n constructor(private bufferTimeSpan: number,\n private bufferCreationInterval: number,\n private maxBufferSize: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new BufferTimeSubscriber(\n subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler\n ));\n }\n}\n\nclass Context {\n buffer: T[] = [];\n closeAction: Subscription;\n}\n\ninterface DispatchCreateArg {\n bufferTimeSpan: number;\n bufferCreationInterval: number;\n subscriber: BufferTimeSubscriber;\n scheduler: SchedulerLike;\n}\n\ninterface DispatchCloseArg {\n subscriber: BufferTimeSubscriber;\n context: Context;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferTimeSubscriber extends Subscriber {\n private contexts: Array> = [];\n private timespanOnly: boolean;\n\n constructor(destination: Subscriber,\n private bufferTimeSpan: number,\n private bufferCreationInterval: number,\n private maxBufferSize: number,\n private scheduler: SchedulerLike) {\n super(destination);\n const context = this.openContext();\n this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;\n if (this.timespanOnly) {\n const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };\n this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));\n } else {\n const closeState = { subscriber: this, context };\n const creationState: DispatchCreateArg = { bufferTimeSpan, bufferCreationInterval, subscriber: this, scheduler };\n this.add(context.closeAction = scheduler.schedule>(dispatchBufferClose, bufferTimeSpan, closeState));\n this.add(scheduler.schedule>(dispatchBufferCreation, bufferCreationInterval, creationState));\n }\n }\n\n protected _next(value: T) {\n const contexts = this.contexts;\n const len = contexts.length;\n let filledBufferContext: Context;\n for (let i = 0; i < len; i++) {\n const context = contexts[i];\n const buffer = context.buffer;\n buffer.push(value);\n if (buffer.length == this.maxBufferSize) {\n filledBufferContext = context;\n }\n }\n\n if (filledBufferContext) {\n this.onBufferFull(filledBufferContext);\n }\n }\n\n protected _error(err: any) {\n this.contexts.length = 0;\n super._error(err);\n }\n\n protected _complete() {\n const { contexts, destination } = this;\n while (contexts.length > 0) {\n const context = contexts.shift();\n destination.next(context.buffer);\n }\n super._complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.contexts = null;\n }\n\n protected onBufferFull(context: Context) {\n this.closeContext(context);\n const closeAction = context.closeAction;\n closeAction.unsubscribe();\n this.remove(closeAction);\n\n if (!this.closed && this.timespanOnly) {\n context = this.openContext();\n const bufferTimeSpan = this.bufferTimeSpan;\n const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };\n this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));\n }\n }\n\n openContext(): Context {\n const context: Context = new Context();\n this.contexts.push(context);\n return context;\n }\n\n closeContext(context: Context) {\n this.destination.next(context.buffer);\n const contexts = this.contexts;\n\n const spliceIndex = contexts ? contexts.indexOf(context) : -1;\n if (spliceIndex >= 0) {\n contexts.splice(contexts.indexOf(context), 1);\n }\n }\n}\n\nfunction dispatchBufferTimeSpanOnly(this: SchedulerAction, state: any) {\n const subscriber: BufferTimeSubscriber = state.subscriber;\n\n const prevContext = state.context;\n if (prevContext) {\n subscriber.closeContext(prevContext);\n }\n\n if (!subscriber.closed) {\n state.context = subscriber.openContext();\n state.context.closeAction = this.schedule(state, state.bufferTimeSpan);\n }\n}\n\nfunction dispatchBufferCreation(this: SchedulerAction>, state: DispatchCreateArg) {\n const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;\n const context = subscriber.openContext();\n const action = >>this;\n if (!subscriber.closed) {\n subscriber.add(context.closeAction = scheduler.schedule>(dispatchBufferClose, bufferTimeSpan, { subscriber, context }));\n action.schedule(state, bufferCreationInterval);\n }\n}\n\nfunction dispatchBufferClose(arg: DispatchCloseArg) {\n const { subscriber, context } = arg;\n subscriber.closeContext(context);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { OperatorFunction, SubscribableOrPromise } from '../types';\n\n/**\n * Buffers the source Observable values starting from an emission from\n * `openings` and ending when the output of `closingSelector` emits.\n *\n * Collects values from the past as an array. Starts\n * collecting only when `opening` emits, and calls the `closingSelector`\n * function to get an Observable that tells when to close the buffer.\n *\n * ![](bufferToggle.png)\n *\n * Buffers values from the source by opening the buffer via signals from an\n * Observable provided to `openings`, and closing and sending the buffers when\n * a Subscribable or Promise returned by the `closingSelector` function emits.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, EMPTY } from 'rxjs';\n * import { bufferToggle } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const buffered = clicks.pipe(bufferToggle(openings, i =>\n * i % 2 ? interval(500) : EMPTY\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferWhen}\n * @see {@link windowToggle}\n *\n * @param {SubscribableOrPromise} openings A Subscribable or Promise of notifications to start new\n * buffers.\n * @param {function(value: O): SubscribableOrPromise} closingSelector A function that takes\n * the value emitted by the `openings` observable and returns a Subscribable or Promise,\n * which, when it emits, signals that the associated buffer should be emitted\n * and cleared.\n * @return {Observable} An observable of arrays of buffered values.\n * @method bufferToggle\n * @owner Observable\n */\nexport function bufferToggle(\n openings: SubscribableOrPromise,\n closingSelector: (value: O) => SubscribableOrPromise\n): OperatorFunction {\n return function bufferToggleOperatorFunction(source: Observable) {\n return source.lift(new BufferToggleOperator(openings, closingSelector));\n };\n}\n\nclass BufferToggleOperator implements Operator {\n\n constructor(private openings: SubscribableOrPromise,\n private closingSelector: (value: O) => SubscribableOrPromise) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));\n }\n}\n\ninterface BufferContext {\n buffer: T[];\n subscription: Subscription;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferToggleSubscriber extends OuterSubscriber {\n private contexts: Array> = [];\n\n constructor(destination: Subscriber,\n private openings: SubscribableOrPromise,\n private closingSelector: (value: O) => SubscribableOrPromise | void) {\n super(destination);\n this.add(subscribeToResult(this, openings));\n }\n\n protected _next(value: T): void {\n const contexts = this.contexts;\n const len = contexts.length;\n for (let i = 0; i < len; i++) {\n contexts[i].buffer.push(value);\n }\n }\n\n protected _error(err: any): void {\n const contexts = this.contexts;\n while (contexts.length > 0) {\n const context = contexts.shift();\n context.subscription.unsubscribe();\n context.buffer = null;\n context.subscription = null;\n }\n this.contexts = null;\n super._error(err);\n }\n\n protected _complete(): void {\n const contexts = this.contexts;\n while (contexts.length > 0) {\n const context = contexts.shift();\n this.destination.next(context.buffer);\n context.subscription.unsubscribe();\n context.buffer = null;\n context.subscription = null;\n }\n this.contexts = null;\n super._complete();\n }\n\n notifyNext(outerValue: any, innerValue: O,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n this.closeBuffer(( innerSub).context);\n }\n\n private openBuffer(value: O): void {\n try {\n const closingSelector = this.closingSelector;\n const closingNotifier = closingSelector.call(this, value);\n if (closingNotifier) {\n this.trySubscribe(closingNotifier);\n }\n } catch (err) {\n this._error(err);\n }\n }\n\n private closeBuffer(context: BufferContext): void {\n const contexts = this.contexts;\n\n if (contexts && context) {\n const { buffer, subscription } = context;\n this.destination.next(buffer);\n contexts.splice(contexts.indexOf(context), 1);\n this.remove(subscription);\n subscription.unsubscribe();\n }\n }\n\n private trySubscribe(closingNotifier: any): void {\n const contexts = this.contexts;\n\n const buffer: Array = [];\n const subscription = new Subscription();\n const context = { buffer, subscription };\n contexts.push(context);\n\n const innerSubscription = subscribeToResult(this, closingNotifier, context);\n\n if (!innerSubscription || innerSubscription.closed) {\n this.closeBuffer(context);\n } else {\n ( innerSubscription).context = context;\n\n this.add(innerSubscription);\n subscription.add(innerSubscription);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Buffers the source Observable values, using a factory function of closing\n * Observables to determine when to close, emit, and reset the buffer.\n *\n * Collects values from the past as an array. When it\n * starts collecting values, it calls a function that returns an Observable that\n * tells when to close the buffer and restart collecting.\n *\n * ![](bufferWhen.png)\n *\n * Opens a buffer immediately, then closes the buffer when the observable\n * returned by calling `closingSelector` function emits a value. When it closes\n * the buffer, it immediately opens a new buffer and repeats the process.\n *\n * ## Example\n *\n * Emit an array of the last clicks every [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { bufferWhen } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferWhen(() =>\n * interval(1000 + Math.random() * 4000)\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link windowWhen}\n *\n * @param {function(): Observable} closingSelector A function that takes no\n * arguments and returns an Observable that signals buffer closure.\n * @return {Observable} An observable of arrays of buffered values.\n * @method bufferWhen\n * @owner Observable\n */\nexport function bufferWhen(closingSelector: () => Observable): OperatorFunction {\n return function (source: Observable) {\n return source.lift(new BufferWhenOperator(closingSelector));\n };\n}\n\nclass BufferWhenOperator implements Operator {\n\n constructor(private closingSelector: () => Observable) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass BufferWhenSubscriber extends OuterSubscriber {\n private buffer: T[];\n private subscribing: boolean = false;\n private closingSubscription: Subscription;\n\n constructor(destination: Subscriber, private closingSelector: () => Observable) {\n super(destination);\n this.openBuffer();\n }\n\n protected _next(value: T) {\n this.buffer.push(value);\n }\n\n protected _complete() {\n const buffer = this.buffer;\n if (buffer) {\n this.destination.next(buffer);\n }\n super._complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.buffer = null;\n this.subscribing = false;\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.openBuffer();\n }\n\n notifyComplete(): void {\n if (this.subscribing) {\n this.complete();\n } else {\n this.openBuffer();\n }\n }\n\n openBuffer() {\n let { closingSubscription } = this;\n\n if (closingSubscription) {\n this.remove(closingSubscription);\n closingSubscription.unsubscribe();\n }\n\n const buffer = this.buffer;\n if (this.buffer) {\n this.destination.next(buffer);\n }\n\n this.buffer = [];\n\n let closingNotifier;\n try {\n const { closingSelector } = this;\n closingNotifier = closingSelector();\n } catch (err) {\n return this.error(err);\n }\n closingSubscription = new Subscription();\n this.closingSubscription = closingSubscription;\n this.add(closingSubscription);\n this.subscribing = true;\n closingSubscription.add(subscribeToResult(this, closingNotifier));\n this.subscribing = false;\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function catchError>(selector: (err: any, caught: Observable) => O): OperatorFunction>;\n/* tslint:enable:max-line-length */\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * ![](catch.png)\n *\n * ## Examples\n * Continues with a different Observable when there's an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n *\t return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V')),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retries the caught source Observable again in case of error, similar to retry() operator\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError, take } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n * \t return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throws a new error when the source Observable throws an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * }),\n * )\n * .subscribe(\n * x => console.log(x),\n * err => console.log(err)\n * );\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again. Whatever observable\n * is returned by the `selector` will be used to continue the observable chain.\n * @return {Observable} An observable that originates from either the source or the observable returned by the\n * catch `selector` function.\n * @name catchError\n */\nexport function catchError>(\n selector: (err: any, caught: Observable) => O\n): OperatorFunction> {\n return function catchErrorOperatorFunction(source: Observable): Observable> {\n const operator = new CatchOperator(selector);\n const caught = source.lift(operator);\n return (operator.caught = caught as Observable);\n };\n}\n\nclass CatchOperator implements Operator {\n caught: Observable;\n\n constructor(private selector: (err: any, caught: Observable) => ObservableInput) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CatchSubscriber extends OuterSubscriber {\n constructor(destination: Subscriber,\n private selector: (err: any, caught: Observable) => ObservableInput,\n private caught: Observable) {\n super(destination);\n }\n\n // NOTE: overriding `error` instead of `_error` because we don't want\n // to have this flag this subscriber as `isStopped`. We can mimic the\n // behavior of the RetrySubscriber (from the `retry` operator), where\n // we unsubscribe from our source chain, reset our Subscriber flags,\n // then subscribe to the selector result.\n error(err: any) {\n if (!this.isStopped) {\n let result: any;\n try {\n result = this.selector(err, this.caught);\n } catch (err2) {\n super.error(err2);\n return;\n }\n this._unsubscribeAndRecycle();\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n this.add(innerSubscriber);\n subscribeToResult(this, result, undefined, undefined, innerSubscriber);\n }\n }\n}\n","import { CombineLatestOperator } from '../observable/combineLatest';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function combineAll(): OperatorFunction, T[]>;\nexport function combineAll(): OperatorFunction;\nexport function combineAll(project: (...values: T[]) => R): OperatorFunction, R>;\nexport function combineAll(project: (...values: Array) => R): OperatorFunction;\n/**\n * Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.\n *\n * ![](combineAll.png)\n *\n * `combineAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,\n * it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that:\n *\n * * Every time an inner Observable emits, the output Observable emits\n * * When the returned observable emits, it emits all of the latest values by:\n * * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they\n * arrived, and the result of the `project` function is what is emitted by the output Observable.\n * * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.\n *\n * ---\n *\n * ## Examples\n *\n * ### Map two click events to a finite interval Observable, then apply `combineAll`\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, combineAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(ev =>\n * interval(Math.random() * 2000).pipe(take(3))\n * ),\n * take(2)\n * );\n * const result = higherOrder.pipe(\n * combineAll()\n * );\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link mergeAll}\n *\n * @param {function(...values: Array)} An optional function to map the most recent values from each inner Observable into a new result.\n * Takes each of the most recent values from each collected inner Observable as arguments, in order.\n * @return {Observable}\n * @name combineAll\n */\nexport function combineAll(project?: (...values: Array) => R): OperatorFunction {\n return (source: Observable) => source.lift(new CombineLatestOperator(project));\n}\n","\nimport { isArray } from '../util/isArray';\nimport { CombineLatestOperator } from '../observable/combineLatest';\nimport { from } from '../observable/from';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\n\nconst none = {};\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(project: (v1: T) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, project: (v1: T, v2: T2) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, project: (v1: T, v2: T2, v3: T3) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): OperatorFunction ;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): OperatorFunction ;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(...observables: Array | ((...values: Array) => R)>): OperatorFunction;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(array: ObservableInput[]): OperatorFunction>;\n/** @deprecated Deprecated in favor of static combineLatest. */\nexport function combineLatest(array: ObservableInput[], project: (v1: T, ...values: Array) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link combineLatest}.\n */\nexport function combineLatest(...observables: Array |\n Array> |\n ((...values: Array) => R)>): OperatorFunction {\n let project: (...values: Array) => R = null;\n if (typeof observables[observables.length - 1] === 'function') {\n project = <(...values: Array) => R>observables.pop();\n }\n\n // if the first and only other argument besides the resultSelector is an array\n // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`\n if (observables.length === 1 && isArray(observables[0])) {\n observables = (observables[0]).slice();\n }\n\n return (source: Observable) => source.lift.call(from([source, ...observables]), new CombineLatestOperator(project));\n}\n","import { concat as concatStatic } from '../observable/concat';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(scheduler?: SchedulerLike): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(v2: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(v2: ObservableInput, v3: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(...observables: Array | SchedulerLike>): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static concat. */\nexport function concat(...observables: Array | SchedulerLike>): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link concat}.\n */\nexport function concat(...observables: Array | SchedulerLike>): OperatorFunction {\n return (source: Observable) => source.lift.call(concatStatic(source, ...observables));\n}\n","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMap>(project: (value: T, index: number) => O): OperatorFunction>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.\n *\n * ![](concatMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item emitted\n * by the source Observable and taking values from each projected inner\n * Observable sequentially.\n * @method concatMap\n * @owner Observable\n */\nexport function concatMap>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R\n): OperatorFunction|R> {\n return mergeMap(project, resultSelector, 1);\n}\n","import { concatMap } from './concatMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMapTo>(observable: O): OperatorFunction>;\n/** @deprecated */\nexport function concatMapTo>(observable: O, resultSelector: undefined): OperatorFunction>;\n/** @deprecated */\nexport function concatMapTo>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in a serialized fashion on the output Observable.\n *\n * It's like {@link concatMap}, but maps each value\n * always to the same inner Observable.\n *\n * ![](concatMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. Each new `innerObservable`\n * instance emitted on the output Observable is concatenated with the previous\n * `innerObservable` instance.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter\n * set to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMapTo, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMapTo(interval(1000).pipe(take(4))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link mergeMapTo}\n * @see {@link switchMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @return {Observable} An observable of values merged together by joining the\n * passed observable with itself, one after the other, for each value emitted\n * from the source.\n * @method concatMapTo\n * @owner Observable\n */\nexport function concatMapTo>(\n innerObservable: O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R\n): OperatorFunction|R> {\n return concatMap(() => innerObservable, resultSelector);\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Observer, OperatorFunction } from '../types';\nimport { Subscriber } from '../Subscriber';\n/**\n * Counts the number of emissions on the source and emits that number when the\n * source completes.\n *\n * Tells how many values were emitted, when the source\n * completes.\n *\n * ![](count.png)\n *\n * `count` transforms an Observable that emits values into an Observable that\n * emits a single value that represents the number of values emitted by the\n * source Observable. If the source Observable terminates with an error, `count`\n * will pass this error notification along without emitting a value first. If\n * the source Observable does not terminate at all, `count` will neither emit\n * a value nor terminate. This operator takes an optional `predicate` function\n * as argument, in which case the output emission will represent the number of\n * source values that matched `true` with the `predicate`.\n *\n * ## Examples\n *\n * Counts how many seconds have passed before the first click happened\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { count, takeUntil } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const secondsBeforeClick = seconds.pipe(takeUntil(clicks));\n * const result = secondsBeforeClick.pipe(count());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Counts how many odd numbers are there between 1 and 7\n * ```ts\n * import { range } from 'rxjs';\n * import { count } from 'rxjs/operators';\n *\n * const numbers = range(1, 7);\n * const result = numbers.pipe(count(i => i % 2 === 1));\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // 4\n * ```\n *\n * @see {@link max}\n * @see {@link min}\n * @see {@link reduce}\n *\n * @param {function(value: T, i: number, source: Observable): boolean} [predicate] A\n * boolean function to select what values are to be counted. It is provided with\n * arguments of:\n * - `value`: the value from the source Observable.\n * - `index`: the (zero-based) \"index\" of the value from the source Observable.\n * - `source`: the source Observable instance itself.\n * @return {Observable} An Observable of one number that represents the count as\n * described above.\n * @method count\n * @owner Observable\n */\n\nexport function count(predicate?: (value: T, index: number, source: Observable) => boolean): OperatorFunction {\n return (source: Observable) => source.lift(new CountOperator(predicate, source));\n}\n\nclass CountOperator implements Operator {\n constructor(private predicate?: (value: T, index: number, source: Observable) => boolean,\n private source?: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CountSubscriber extends Subscriber {\n private count: number = 0;\n private index: number = 0;\n\n constructor(destination: Observer,\n private predicate?: (value: T, index: number, source: Observable) => boolean,\n private source?: Observable) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.predicate) {\n this._tryPredicate(value);\n } else {\n this.count++;\n }\n }\n\n private _tryPredicate(value: T) {\n let result: any;\n\n try {\n result = this.predicate(value, this.index++, this.source);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n\n if (result) {\n this.count++;\n }\n }\n\n protected _complete(): void {\n this.destination.next(this.count);\n this.destination.complete();\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * determined by another Observable has passed without another source emission.\n *\n * It's like {@link debounceTime}, but the time span of\n * emission silence is determined by a second Observable.\n *\n * ![](debounce.png)\n *\n * `debounce` delays values emitted by the source Observable, but drops previous\n * pending delayed emissions if a new value arrives on the source Observable.\n * This operator keeps track of the most recent value from the source\n * Observable, and spawns a duration Observable by calling the\n * `durationSelector` function. The value is emitted only when the duration\n * Observable emits a value or completes, and if no other value was emitted on\n * the source Observable since the duration Observable was spawned. If a new\n * value appears before the duration Observable emits, the previous value will\n * be dropped and will not be emitted on the output Observable.\n *\n * Like {@link debounceTime}, this is a rate-limiting operator, and also a\n * delay-like operator since output emissions do not necessarily occur at the\n * same time as they did on the source Observable.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { debounce } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounce(() => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n * @see {@link throttle}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the timeout\n * duration for each source value, returned as an Observable or a Promise.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified duration Observable returned by\n * `durationSelector`, and may drop some values if they occur too frequently.\n * @method debounce\n * @owner Observable\n */\nexport function debounce(durationSelector: (value: T) => SubscribableOrPromise): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new DebounceOperator(durationSelector));\n}\n\nclass DebounceOperator implements Operator {\n constructor(private durationSelector: (value: T) => SubscribableOrPromise) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceSubscriber extends OuterSubscriber {\n private value: T;\n private hasValue: boolean = false;\n private durationSubscription: Subscription = null;\n\n constructor(destination: Subscriber,\n private durationSelector: (value: T) => SubscribableOrPromise) {\n super(destination);\n }\n\n protected _next(value: T): void {\n try {\n const result = this.durationSelector.call(this, value);\n\n if (result) {\n this._tryNext(value, result);\n }\n } catch (err) {\n this.destination.error(err);\n }\n }\n\n protected _complete(): void {\n this.emitValue();\n this.destination.complete();\n }\n\n private _tryNext(value: T, duration: SubscribableOrPromise): void {\n let subscription = this.durationSubscription;\n this.value = value;\n this.hasValue = true;\n if (subscription) {\n subscription.unsubscribe();\n this.remove(subscription);\n }\n\n subscription = subscribeToResult(this, duration);\n if (subscription && !subscription.closed) {\n this.add(this.durationSubscription = subscription);\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.emitValue();\n }\n\n notifyComplete(): void {\n this.emitValue();\n }\n\n emitValue(): void {\n if (this.hasValue) {\n const value = this.value;\n const subscription = this.durationSubscription;\n if (subscription) {\n this.durationSubscription = null;\n subscription.unsubscribe();\n this.remove(subscription);\n }\n // This must be done *before* passing the value\n // along to the destination because it's possible for\n // the value to synchronously re-enter this operator\n // recursively if the duration selector Observable\n // emits synchronously\n this.value = null;\n this.hasValue = false;\n super._next(value);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * It's like {@link delay}, but passes only the most\n * recent value from each burst of emissions.\n *\n * ![](debounceTime.png)\n *\n * `debounceTime` delays values emitted by the source Observable, but drops\n * previous pending delayed emissions if a new value arrives on the source\n * Observable. This operator keeps track of the most recent value from the\n * source Observable, and emits that only when `dueTime` enough time has passed\n * without any other value appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous value will be dropped\n * and will not be emitted on the output Observable.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * value to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { debounceTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} dueTime The timeout duration in milliseconds (or the time\n * unit determined internally by the optional `scheduler`) for the window of\n * time required to wait for emission silence before emitting the most recent\n * source value.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the timeout for each value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified `dueTime`, and may drop some values if they occur\n * too frequently.\n * @method debounceTime\n * @owner Observable\n */\nexport function debounceTime(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new DebounceTimeOperator(dueTime, scheduler));\n}\n\nclass DebounceTimeOperator implements Operator {\n constructor(private dueTime: number, private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceTimeSubscriber extends Subscriber {\n private debouncedSubscription: Subscription = null;\n private lastValue: T = null;\n private hasValue: boolean = false;\n\n constructor(destination: Subscriber,\n private dueTime: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n protected _next(value: T) {\n this.clearDebounce();\n this.lastValue = value;\n this.hasValue = true;\n this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));\n }\n\n protected _complete() {\n this.debouncedNext();\n this.destination.complete();\n }\n\n debouncedNext(): void {\n this.clearDebounce();\n\n if (this.hasValue) {\n const { lastValue } = this;\n // This must be done *before* passing the value\n // along to the destination because it's possible for\n // the value to synchronously re-enter this operator\n // recursively when scheduled with things like\n // VirtualScheduler/TestScheduler.\n this.lastValue = null;\n this.hasValue = false;\n this.destination.next(lastValue);\n }\n }\n\n private clearDebounce(): void {\n const debouncedSubscription = this.debouncedSubscription;\n\n if (debouncedSubscription !== null) {\n this.remove(debouncedSubscription);\n debouncedSubscription.unsubscribe();\n this.debouncedSubscription = null;\n }\n }\n}\n\nfunction dispatchNext(subscriber: DebounceTimeSubscriber) {\n subscriber.debouncedNext();\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function defaultIfEmpty(defaultValue?: T): MonoTypeOperatorFunction;\nexport function defaultIfEmpty(defaultValue?: R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Emits a given value if the source Observable completes without emitting any\n * `next` value, otherwise mirrors the source Observable.\n *\n * If the source Observable turns out to be empty, then\n * this operator will emit a default value.\n *\n * ![](defaultIfEmpty.png)\n *\n * `defaultIfEmpty` emits the values emitted by the source Observable or a\n * specified default value if the source Observable is empty (completes without\n * having emitted any `next` value).\n *\n * ## Example\n * If no clicks happen in 5 seconds, then emit \"no clicks\"\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { defaultIfEmpty, takeUntil } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));\n * const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link empty}\n * @see {@link last}\n *\n * @param {any} [defaultValue=null] The default value used if the source\n * Observable is empty.\n * @return {Observable} An Observable that emits either the specified\n * `defaultValue` if the source Observable emits no items, or the values emitted\n * by the source Observable.\n * @method defaultIfEmpty\n * @owner Observable\n */\nexport function defaultIfEmpty(defaultValue: R = null): OperatorFunction {\n return (source: Observable) => source.lift(new DefaultIfEmptyOperator(defaultValue)) as Observable;\n}\n\nclass DefaultIfEmptyOperator implements Operator {\n\n constructor(private defaultValue: R) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DefaultIfEmptySubscriber extends Subscriber {\n private isEmpty: boolean = true;\n\n constructor(destination: Subscriber, private defaultValue: R) {\n super(destination);\n }\n\n protected _next(value: T): void {\n this.isEmpty = false;\n this.destination.next(value);\n }\n\n protected _complete(): void {\n if (this.isEmpty) {\n this.destination.next(this.defaultValue);\n }\n this.destination.complete();\n }\n}\n","export function isDate(value: any): value is Date {\n return value instanceof Date && !isNaN(+value);\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * Time shifts each item by some specified amount of\n * milliseconds.\n *\n * ![](delay.png)\n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n * Delay each click by one second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n *\n * @param {number|Date} delay The delay duration in milliseconds (a `number`) or\n * a `Date` until which the emission of the source items is delayed.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the time-shift for each item.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified timeout or Date.\n * @method delay\n * @owner Observable\n */\nexport function delay(delay: number|Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction {\n const absoluteDelay = isDate(delay);\n const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);\n return (source: Observable) => source.lift(new DelayOperator(delayFor, scheduler));\n}\n\nclass DelayOperator implements Operator {\n constructor(private delay: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n }\n}\n\ninterface DelayState {\n source: DelaySubscriber;\n destination: PartialObserver;\n scheduler: SchedulerLike;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelaySubscriber extends Subscriber {\n private queue: Array> = [];\n private active: boolean = false;\n private errored: boolean = false;\n\n private static dispatch(this: SchedulerAction>, state: DelayState): void {\n const source = state.source;\n const queue = source.queue;\n const scheduler = state.scheduler;\n const destination = state.destination;\n\n while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {\n queue.shift().notification.observe(destination);\n }\n\n if (queue.length > 0) {\n const delay = Math.max(0, queue[0].time - scheduler.now());\n this.schedule(state, delay);\n } else {\n this.unsubscribe();\n source.active = false;\n }\n }\n\n constructor(destination: Subscriber,\n private delay: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n private _schedule(scheduler: SchedulerLike): void {\n this.active = true;\n const destination = this.destination as Subscription;\n destination.add(scheduler.schedule>(DelaySubscriber.dispatch, this.delay, {\n source: this, destination: this.destination, scheduler: scheduler\n }));\n }\n\n private scheduleNotification(notification: Notification): void {\n if (this.errored === true) {\n return;\n }\n\n const scheduler = this.scheduler;\n const message = new DelayMessage(scheduler.now() + this.delay, notification);\n this.queue.push(message);\n\n if (this.active === false) {\n this._schedule(scheduler);\n }\n }\n\n protected _next(value: T) {\n this.scheduleNotification(Notification.createNext(value));\n }\n\n protected _error(err: any) {\n this.errored = true;\n this.queue = [];\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete() {\n this.scheduleNotification(Notification.createComplete());\n this.unsubscribe();\n }\n}\n\nclass DelayMessage {\n constructor(public readonly time: number,\n public readonly notification: Notification) {\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated In future versions, empty notifiers will no longer re-emit the source value on the output observable. */\nexport function delayWhen(delayDurationSelector: (value: T, index: number) => Observable, subscriptionDelay?: Observable): MonoTypeOperatorFunction;\nexport function delayWhen(delayDurationSelector: (value: T, index: number) => Observable, subscriptionDelay?: Observable): MonoTypeOperatorFunction;\n/* tslint:disable:max-line-length */\n\n/**\n * Delays the emission of items from the source Observable by a given time span\n * determined by the emissions of another Observable.\n *\n * It's like {@link delay}, but the time span of the\n * delay duration is determined by a second Observable.\n *\n * ![](delayWhen.png)\n *\n * `delayWhen` time shifts each emitted value from the source Observable by a\n * time span determined by another Observable. When the source emits a value,\n * the `delayDurationSelector` function is called with the source value as\n * argument, and should return an Observable, called the \"duration\" Observable.\n * The source value is emitted on the output Observable only when the duration\n * Observable emits a value or completes.\n * The completion of the notifier triggering the emission of the source value\n * is deprecated behavior and will be removed in future versions.\n *\n * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which\n * is an Observable. When `subscriptionDelay` emits its first value or\n * completes, the source Observable is subscribed to and starts behaving like\n * described in the previous paragraph. If `subscriptionDelay` is not provided,\n * `delayWhen` will subscribe to the source Observable as soon as the output\n * Observable is subscribed.\n *\n * ## Example\n * Delay each click by a random amount of time, between 0 and 5 seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { delayWhen } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(\n * delayWhen(event => interval(Math.random() * 5000)),\n * );\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link debounce}\n * @see {@link delay}\n *\n * @param {function(value: T, index: number): Observable} delayDurationSelector A function that\n * returns an Observable for each value emitted by the source Observable, which\n * is then used to delay the emission of that item on the output Observable\n * until the Observable returned from this function emits a value.\n * @param {Observable} subscriptionDelay An Observable that triggers the\n * subscription to the source Observable once it emits any value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by an amount of time specified by the Observable returned by\n * `delayDurationSelector`.\n * @method delayWhen\n * @owner Observable\n */\nexport function delayWhen(delayDurationSelector: (value: T, index: number) => Observable,\n subscriptionDelay?: Observable): MonoTypeOperatorFunction {\n if (subscriptionDelay) {\n return (source: Observable) =>\n new SubscriptionDelayObservable(source, subscriptionDelay)\n .lift(new DelayWhenOperator(delayDurationSelector));\n }\n return (source: Observable) => source.lift(new DelayWhenOperator(delayDurationSelector));\n}\n\nclass DelayWhenOperator implements Operator {\n constructor(private delayDurationSelector: (value: T, index: number) => Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelayWhenSubscriber extends OuterSubscriber {\n private completed: boolean = false;\n private delayNotifierSubscriptions: Array = [];\n private index: number = 0;\n\n constructor(destination: Subscriber,\n private delayDurationSelector: (value: T, index: number) => Observable) {\n super(destination);\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.destination.next(outerValue);\n this.removeSubscription(innerSub);\n this.tryComplete();\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this._error(error);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n const value = this.removeSubscription(innerSub);\n if (value) {\n this.destination.next(value);\n }\n this.tryComplete();\n }\n\n protected _next(value: T): void {\n const index = this.index++;\n try {\n const delayNotifier = this.delayDurationSelector(value, index);\n if (delayNotifier) {\n this.tryDelay(delayNotifier, value);\n }\n } catch (err) {\n this.destination.error(err);\n }\n }\n\n protected _complete(): void {\n this.completed = true;\n this.tryComplete();\n this.unsubscribe();\n }\n\n private removeSubscription(subscription: InnerSubscriber): T {\n subscription.unsubscribe();\n\n const subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);\n if (subscriptionIdx !== -1) {\n this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);\n }\n\n return subscription.outerValue;\n }\n\n private tryDelay(delayNotifier: Observable, value: T): void {\n const notifierSubscription = subscribeToResult(this, delayNotifier, value);\n\n if (notifierSubscription && !notifierSubscription.closed) {\n const destination = this.destination as Subscription;\n destination.add(notifierSubscription);\n this.delayNotifierSubscriptions.push(notifierSubscription);\n }\n }\n\n private tryComplete(): void {\n if (this.completed && this.delayNotifierSubscriptions.length === 0) {\n this.destination.complete();\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SubscriptionDelayObservable extends Observable {\n constructor(public source: Observable, private subscriptionDelay: Observable) {\n super();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber) {\n this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SubscriptionDelaySubscriber extends Subscriber {\n private sourceSubscribed: boolean = false;\n\n constructor(private parent: Subscriber, private source: Observable) {\n super();\n }\n\n protected _next(unused: any) {\n this.subscribeToSource();\n }\n\n protected _error(err: any) {\n this.unsubscribe();\n this.parent.error(err);\n }\n\n protected _complete() {\n this.unsubscribe();\n this.subscribeToSource();\n }\n\n private subscribeToSource(): void {\n if (!this.sourceSubscribed) {\n this.sourceSubscribed = true;\n this.unsubscribe();\n this.source.subscribe(this.parent);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nimport { OperatorFunction } from '../types';\n\n/**\n * Converts an Observable of {@link Notification} objects into the emissions\n * that they represent.\n *\n * Unwraps {@link Notification} objects as actual `next`,\n * `error` and `complete` emissions. The opposite of {@link materialize}.\n *\n * ![](dematerialize.png)\n *\n * `dematerialize` is assumed to operate an Observable that only emits\n * {@link Notification} objects as `next` emissions, and does not emit any\n * `error`. Such Observable is the output of a `materialize` operation. Those\n * notifications are then unwrapped using the metadata they contain, and emitted\n * as `next`, `error`, and `complete` on the output Observable.\n *\n * Use this operator in conjunction with {@link materialize}.\n *\n * ## Example\n * Convert an Observable of Notifications to an actual Observable\n * ```ts\n * import { of, Notification } from 'rxjs';\n * import { dematerialize } from 'rxjs/operators';\n *\n * const notifA = new Notification('N', 'A');\n * const notifB = new Notification('N', 'B');\n * const notifE = new Notification('E', undefined,\n * new TypeError('x.toUpperCase is not a function')\n * );\n * const materialized = of(notifA, notifB, notifE);\n * const upperCase = materialized.pipe(dematerialize());\n * upperCase.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Results in:\n * // A\n * // B\n * // TypeError: x.toUpperCase is not a function\n * ```\n *\n * @see {@link Notification}\n * @see {@link materialize}\n *\n * @return {Observable} An Observable that emits items and notifications\n * embedded in Notification objects emitted by the source Observable.\n * @method dematerialize\n * @owner Observable\n */\nexport function dematerialize(): OperatorFunction, T> {\n return function dematerializeOperatorFunction(source: Observable>) {\n return source.lift(new DeMaterializeOperator());\n };\n}\n\nclass DeMaterializeOperator, R> implements Operator {\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new DeMaterializeSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DeMaterializeSubscriber> extends Subscriber {\n constructor(destination: Subscriber) {\n super(destination);\n }\n\n protected _next(value: T) {\n value.observe(this.destination);\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.\n *\n * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will\n * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the\n * source observable directly with an equality check against previous values.\n *\n * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.\n *\n * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the\n * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`\n * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so\n * that the internal `Set` can be \"flushed\", basically clearing it of values.\n *\n * ## Examples\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinct } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe(\n * distinct(),\n * )\n * .subscribe(x => console.log(x)); // 1, 2, 3, 4\n * ```\n *\n * An example using a keySelector function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinct } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'},\n * ).pipe(\n * distinct((p: Person) => p.name),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * ```\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [keySelector] Optional function to select which value you want to check as distinct.\n * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinct\n * @owner Observable\n */\nexport function distinct(keySelector?: (value: T) => K,\n flushes?: Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new DistinctOperator(keySelector, flushes));\n}\n\nclass DistinctOperator implements Operator {\n constructor(private keySelector: (value: T) => K, private flushes: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class DistinctSubscriber extends OuterSubscriber {\n private values = new Set();\n\n constructor(destination: Subscriber, private keySelector: (value: T) => K, flushes: Observable) {\n super(destination);\n\n if (flushes) {\n this.add(subscribeToResult(this, flushes));\n }\n }\n\n notifyNext(outerValue: T, innerValue: T,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.values.clear();\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this._error(error);\n }\n\n protected _next(value: T): void {\n if (this.keySelector) {\n this._useKeySelector(value);\n } else {\n this._finalizeNext(value, value);\n }\n }\n\n private _useKeySelector(value: T): void {\n let key: K;\n const { destination } = this;\n try {\n key = this.keySelector(value);\n } catch (err) {\n destination.error(err);\n return;\n }\n this._finalizeNext(key, value);\n }\n\n private _finalizeNext(key: K|T, value: T) {\n const { values } = this;\n if (!values.has(key)) {\n values.add(key);\n this.destination.next(value);\n }\n }\n\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilChanged(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction;\nexport function distinctUntilChanged(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.\n *\n * It's like {@link filter}, but just emits the values that are distinct from the previous.\n *\n * ![](distinctUntilChanged.png)\n *\n * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Example\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(\n * distinctUntilChanged(),\n * )\n * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4\n * ```\n *\n * An example using a compare function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'},\n * { age: 6, name: 'Foo'},\n * ).pipe(\n * distinctUntilChanged((p: Person, q: Person) => p.name === q.name),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinctUntilChanged\n * @owner Observable\n */\nexport function distinctUntilChanged(compare?: (x: K, y: K) => boolean, keySelector?: (x: T) => K): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new DistinctUntilChangedOperator(compare, keySelector));\n}\n\nclass DistinctUntilChangedOperator implements Operator {\n constructor(private compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DistinctUntilChangedSubscriber extends Subscriber {\n private key: K;\n private hasKey: boolean = false;\n\n constructor(destination: Subscriber,\n compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n super(destination);\n if (typeof compare === 'function') {\n this.compare = compare;\n }\n }\n\n private compare(x: any, y: any): boolean {\n return x === y;\n }\n\n protected _next(value: T): void {\n let key: any;\n try {\n const { keySelector } = this;\n key = keySelector ? keySelector(value) : value;\n } catch (err) {\n return this.destination.error(err);\n }\n let result = false;\n if (this.hasKey) {\n try {\n const { compare } = this;\n result = compare(this.key, key);\n } catch (err) {\n return this.destination.error(err);\n }\n } else {\n this.hasKey = true;\n }\n if (!result) {\n this.key = key;\n this.destination.next(value);\n }\n }\n}\n","import { distinctUntilChanged } from './distinctUntilChanged';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilKeyChanged(key: keyof T): MonoTypeOperatorFunction;\nexport function distinctUntilKeyChanged(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item,\n * using a property accessed by using the key provided to check if the two items are distinct.\n *\n * It's like {@link distinctUntilChanged}, but the distinct comparison uses a key to access a property.\n *\n * ![](distinctUntilKeyChanged.png)\n *\n * `distinctUntilKeyChanged` emits all items of the source Observable, wich are distinct by comparison.\n * The comparison checks if the previous item is distinct from the current item, using a `key` to access a property.\n * If a comparator function is provided, then it will be called for each item with the property key\n * to test for whether or not that value should be emitted.\n *\n * ## Examples\n * An example comparing the name of persons\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilKeyChanged } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'},\n * { age: 6, name: 'Foo'},\n * ).pipe(\n * distinctUntilKeyChanged('name'),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * An example comparing the first letters of the name\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilKeyChanged } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of(\n * { age: 4, name: 'Foo1'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo2'},\n * { age: 6, name: 'Foo3'},\n * ).pipe(\n * distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3)),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo1' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo2' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n *\n * @param {string} key String key for object property lookup on each item.\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values based on the key specified.\n * @method distinctUntilKeyChanged\n * @owner Observable\n */\nexport function distinctUntilKeyChanged(key: K, compare?: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction {\n return distinctUntilChanged((x: T, y: T) => compare ? compare(x[key], y[key]) : x[key] === y[key]);\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { TeardownLogic, MonoTypeOperatorFunction } from '../types';\n\n/**\n * If the source observable completes without emitting a value, it will emit\n * an error. The error will be created at that time by the optional\n * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.\n *\n * ![](throwIfEmpty.png)\n *\n * ## Example\n * ```ts\n * import { fromEvent, timer } from 'rxjs';\n * import { throwIfEmpty, takeUntil } from 'rxjs/operators';\n *\n * const click$ = fromEvent(document, 'click');\n *\n * click$.pipe(\n * takeUntil(timer(1000)),\n * throwIfEmpty(\n * () => new Error('the document was not clicked within 1 second')\n * ),\n * )\n * .subscribe({\n * next() { console.log('The button was clicked'); },\n * error(err) { console.error(err); }\n * });\n * ```\n *\n * @param errorFactory A factory function called to produce the\n * error to be thrown when the source observable completes without emitting a\n * value.\n */\nexport function throwIfEmpty (errorFactory: (() => any) = defaultErrorFactory): MonoTypeOperatorFunction {\n return (source: Observable) => {\n return source.lift(new ThrowIfEmptyOperator(errorFactory));\n };\n}\n\nclass ThrowIfEmptyOperator implements Operator {\n constructor(private errorFactory: () => any) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));\n }\n}\n\nclass ThrowIfEmptySubscriber extends Subscriber {\n private hasValue: boolean = false;\n\n constructor(destination: Subscriber, private errorFactory: () => any) {\n super(destination);\n }\n\n protected _next(value: T): void {\n this.hasValue = true;\n this.destination.next(value);\n }\n\n protected _complete() {\n if (!this.hasValue) {\n let err: any;\n try {\n err = this.errorFactory();\n } catch (e) {\n err = e;\n }\n this.destination.error(err);\n } else {\n return this.destination.complete();\n }\n }\n}\n\nfunction defaultErrorFactory() {\n return new EmptyError();\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * Takes the first `count` values from the source, then\n * completes.\n *\n * ![](take.png)\n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n * Take the first 5 seconds of an infinite 1-second interval Observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of `next` values to emit.\n * @return {Observable} An Observable that emits only the first `count`\n * values emitted by the source Observable, or all of the values from the source\n * if the source emits fewer than `count` values.\n * @method take\n * @owner Observable\n */\nexport function take(count: number): MonoTypeOperatorFunction {\n return (source: Observable) => {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeOperator(count));\n }\n };\n}\n\nclass TakeOperator implements Operator {\n constructor(private total: number) {\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError;\n }\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new TakeSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeSubscriber extends Subscriber {\n private count: number = 0;\n\n constructor(destination: Subscriber, private total: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const total = this.total;\n const count = ++this.count;\n if (count <= total) {\n this.destination.next(value);\n if (count === total) {\n this.destination.complete();\n this.unsubscribe();\n }\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\nimport { filter } from './filter';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { take } from './take';\n\n/**\n * Emits the single value at the specified `index` in a sequence of emissions\n * from the source Observable.\n *\n * Emits only the i-th value, then completes.\n *\n * ![](elementAt.png)\n *\n * `elementAt` returns an Observable that emits the item at the specified\n * `index` in the source Observable, or a default value if that `index` is out\n * of range and the `default` argument is provided. If the `default` argument is\n * not given and the `index` is out of range, the output Observable will emit an\n * `ArgumentOutOfRangeError` error.\n *\n * ## Example\n * Emit only the third click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { elementAt } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(elementAt(2));\n * result.subscribe(x => console.log(x));\n *\n * // Results in:\n * // click 1 = nothing\n * // click 2 = nothing\n * // click 3 = MouseEvent object logged to console\n * ```\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link skip}\n * @see {@link single}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the\n * Observable has completed before emitting the i-th `next` notification.\n *\n * @param {number} index Is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {T} [defaultValue] The default value returned for missing indices.\n * @return {Observable} An Observable that emits a single item, if it is found.\n * Otherwise, will emit the default value if given. If not, then emits an error.\n * @method elementAt\n * @owner Observable\n */\nexport function elementAt(index: number, defaultValue?: T): MonoTypeOperatorFunction {\n if (index < 0) { throw new ArgumentOutOfRangeError(); }\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable) => source.pipe(\n filter((v, i) => i === index),\n take(1),\n hasDefaultValue\n ? defaultIfEmpty(defaultValue)\n : throwIfEmpty(() => new ArgumentOutOfRangeError()),\n );\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { of } from '../observable/of';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(scheduler: SchedulerLike): MonoTypeOperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, v2: B, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, v2: B, v3: C, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, v2: B, v3: C, v4: D, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, v2: B, v3: C, v4: D, v5: E, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F, scheduler: SchedulerLike): OperatorFunction;\n\nexport function endWith(v1: A): OperatorFunction;\nexport function endWith(v1: A, v2: B): OperatorFunction;\nexport function endWith(v1: A, v2: B, v3: C): OperatorFunction;\nexport function endWith(v1: A, v2: B, v3: C, v4: D): OperatorFunction;\nexport function endWith(v1: A, v2: B, v3: C, v4: D, v5: E): OperatorFunction;\nexport function endWith(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F): OperatorFunction;\nexport function endWith(...array: Z[]): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */\nexport function endWith(...array: Array): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments after it finishes emitting\n * items emitted by the source Observable.\n *\n * ![](endWith.png)\n *\n * ## Example\n * ### After the source observable completes, appends an emission and then completes too.\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { endWith } from 'rxjs/operators';\n *\n * of('hi', 'how are you?', 'sorry, I have to go now').pipe(\n * endWith('goodbye!'),\n * )\n * .subscribe(word => console.log(word));\n * // result:\n * // 'hi'\n * // 'how are you?'\n * // 'sorry, I have to go now'\n * // 'goodbye!'\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit last.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items emitted by the source Observable\n * and then emits the items in the specified Iterable.\n * @method endWith\n * @owner Observable\n */\nexport function endWith(...array: Array): MonoTypeOperatorFunction {\n return (source: Observable) => concat(source, of(...array)) as Observable;\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Observer, OperatorFunction } from '../types';\n\n/**\n * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.\n *\n * ## Example\n * A simple example emitting true if all elements are less than 5, false otherwise\n * ```ts\n * import { of } from 'rxjs';\n * import { every } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5, 6).pipe(\n * every(x => x < 5),\n * )\n * .subscribe(x => console.log(x)); // -> false\n * ```\n *\n * @param {function} predicate A function for determining if an item meets a specified condition.\n * @param {any} [thisArg] Optional object to use for `this` in the callback.\n * @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.\n * @method every\n * @owner Observable\n */\nexport function every(predicate: (value: T, index: number, source: Observable) => boolean,\n thisArg?: any): OperatorFunction {\n return (source: Observable) => source.lift(new EveryOperator(predicate, thisArg, source));\n}\n\nclass EveryOperator implements Operator {\n constructor(private predicate: (value: T, index: number, source: Observable) => boolean,\n private thisArg?: any,\n private source?: Observable) {\n }\n\n call(observer: Subscriber, source: any): any {\n return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass EverySubscriber extends Subscriber {\n private index: number = 0;\n\n constructor(destination: Observer,\n private predicate: (value: T, index: number, source: Observable) => boolean,\n private thisArg: any,\n private source?: Observable) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n private notifyComplete(everyValueMatch: boolean): void {\n this.destination.next(everyValueMatch);\n this.destination.complete();\n }\n\n protected _next(value: T): void {\n let result = false;\n try {\n result = this.predicate.call(this.thisArg, value, this.index++, this.source);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n\n if (!result) {\n this.notifyComplete(false);\n }\n }\n\n protected _complete(): void {\n this.notifyComplete(true);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, TeardownLogic } from '../types';\n\nexport function exhaust(): OperatorFunction, T>;\nexport function exhaust(): OperatorFunction;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by dropping\n * inner Observables while the previous inner Observable has not yet completed.\n *\n * Flattens an Observable-of-Observables by dropping the\n * next inner Observables while the current inner is still executing.\n *\n * ![](exhaust.png)\n *\n * `exhaust` subscribes to an Observable that emits Observables, also known as a\n * higher-order Observable. Each time it observes one of these emitted inner\n * Observables, the output Observable begins emitting the items emitted by that\n * inner Observable. So far, it behaves like {@link mergeAll}. However,\n * `exhaust` ignores every new inner Observable if the previous Observable has\n * not yet completed. Once that one completes, it will accept and flatten the\n * next inner Observable and repeat this process.\n *\n * ## Example\n * Run a finite timer for each click, only if there is no currently active timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { exhaust, map, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map((ev) => interval(1000).pipe(take(5))),\n * );\n * const result = higherOrder.pipe(exhaust());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeAll}\n * @see {@link exhaustMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable that takes a source of Observables and propagates the first observable\n * exclusively until it completes before subscribing to the next.\n * @method exhaust\n * @owner Observable\n */\nexport function exhaust(): OperatorFunction {\n return (source: Observable) => source.lift(new SwitchFirstOperator());\n}\n\nclass SwitchFirstOperator implements Operator {\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SwitchFirstSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchFirstSubscriber extends OuterSubscriber {\n private hasCompleted: boolean = false;\n private hasSubscription: boolean = false;\n\n constructor(destination: Subscriber) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (!this.hasSubscription) {\n this.hasSubscription = true;\n this.add(subscribeToResult(this, value));\n }\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (!this.hasSubscription) {\n this.destination.complete();\n }\n }\n\n notifyComplete(innerSub: Subscription): void {\n this.remove(innerSub);\n this.hasSubscription = false;\n if (this.hasCompleted) {\n this.destination.complete();\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\n\n/* tslint:disable:max-line-length */\nexport function exhaustMap>(project: (value: T, index: number) => O): OperatorFunction>;\n/** @deprecated resultSelector is no longer supported. Use inner map instead. */\nexport function exhaustMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>;\n/** @deprecated resultSelector is no longer supported. Use inner map instead. */\nexport function exhaustMap(project: (value: T, index: number) => ObservableInput, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable only if the previous projected Observable has completed.\n *\n * Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link exhaust}.\n *\n * ![](exhaustMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. When it projects a source value to\n * an Observable, the output Observable begins emitting the items emitted by\n * that projected Observable. However, `exhaustMap` ignores every new projected\n * Observable if the previous projected Observable has not yet completed. Once\n * that one completes, it will accept and flatten the next projected Observable\n * and repeat this process.\n *\n * ## Example\n * Run a finite timer for each click, only if there is no currently active timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { exhaustMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * exhaustMap(ev => interval(1000).pipe(take(5)))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaust}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable containing projected Observables\n * of each item of the source, ignoring projected Observables that start before\n * their preceding Observable has completed.\n * @method exhaustMap\n * @owner Observable\n */\nexport function exhaustMap>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction|R> {\n if (resultSelector) {\n // DEPRECATED PATH\n return (source: Observable) => source.pipe(\n exhaustMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: any) => resultSelector(a, b, i, ii)),\n )),\n );\n }\n return (source: Observable) =>\n source.lift(new ExhaustMapOperator(project));\n}\n\nclass ExhaustMapOperator implements Operator {\n constructor(private project: (value: T, index: number) => ObservableInput) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ExhaustMapSubscriber extends OuterSubscriber {\n private hasSubscription = false;\n private hasCompleted = false;\n private index = 0;\n\n constructor(destination: Subscriber,\n private project: (value: T, index: number) => ObservableInput) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (!this.hasSubscription) {\n this.tryNext(value);\n }\n }\n\n private tryNext(value: T): void {\n let result: ObservableInput;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.hasSubscription = true;\n this._innerSub(result, value, index);\n }\n\n private _innerSub(result: ObservableInput, value: T, index: number): void {\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n subscribeToResult(this, result, value, index, innerSubscriber);\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (!this.hasSubscription) {\n this.destination.complete();\n }\n this.unsubscribe();\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.destination.next(innerValue);\n }\n\n notifyError(err: any): void {\n this.destination.error(err);\n }\n\n notifyComplete(innerSub: Subscription): void {\n const destination = this.destination as Subscription;\n destination.remove(innerSub);\n\n this.hasSubscription = false;\n if (this.hasCompleted) {\n this.destination.complete();\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { MonoTypeOperatorFunction, OperatorFunction, ObservableInput, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function expand(project: (value: T, index: number) => ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\nexport function expand(project: (value: T, index: number) => ObservableInput, concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Recursively projects each source value to an Observable which is merged in\n * the output Observable.\n *\n * It's similar to {@link mergeMap}, but applies the\n * projection function to every source value as well as every output value.\n * It's recursive.\n *\n * ![](expand.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger. *Expand* will re-emit on the output\n * Observable every source value. Then, each output value is given to the\n * `project` function which returns an inner Observable to be merged on the\n * output Observable. Those output values resulting from the projection are also\n * given to the `project` function to produce new output values. This is how\n * *expand* behaves recursively.\n *\n * ## Example\n * Start emitting the powers of two on every click, at most 10 of them\n * ```ts\n * import { fromEvent, of } from 'rxjs';\n * import { expand, mapTo, delay, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const powersOfTwo = clicks.pipe(\n * mapTo(1),\n * expand(x => of(2 * x).pipe(delay(1000))),\n * take(10),\n * );\n * powersOfTwo.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n *\n * @param {function(value: T, index: number) => Observable} project A function\n * that, when applied to an item emitted by the source or the output Observable,\n * returns an Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to\n * each projected inner Observable.\n * @return {Observable} An Observable that emits the source values and also\n * result of applying the projection function to each value emitted on the\n * output Observable and and merging the results of the Observables obtained\n * from this transformation.\n * @method expand\n * @owner Observable\n */\nexport function expand(project: (value: T, index: number) => ObservableInput,\n concurrent: number = Number.POSITIVE_INFINITY,\n scheduler: SchedulerLike = undefined): OperatorFunction {\n concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;\n\n return (source: Observable) => source.lift(new ExpandOperator(project, concurrent, scheduler));\n}\n\nexport class ExpandOperator implements Operator {\n constructor(private project: (value: T, index: number) => ObservableInput,\n private concurrent: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));\n }\n}\n\ninterface DispatchArg {\n subscriber: ExpandSubscriber;\n result: ObservableInput;\n value: any;\n index: number;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class ExpandSubscriber extends OuterSubscriber {\n private index: number = 0;\n private active: number = 0;\n private hasCompleted: boolean = false;\n private buffer: any[];\n\n constructor(destination: Subscriber,\n private project: (value: T, index: number) => ObservableInput,\n private concurrent: number,\n private scheduler: SchedulerLike) {\n super(destination);\n if (concurrent < Number.POSITIVE_INFINITY) {\n this.buffer = [];\n }\n }\n\n private static dispatch(arg: DispatchArg): void {\n const {subscriber, result, value, index} = arg;\n subscriber.subscribeToProjection(result, value, index);\n }\n\n protected _next(value: any): void {\n const destination = this.destination;\n\n if (destination.closed) {\n this._complete();\n return;\n }\n\n const index = this.index++;\n if (this.active < this.concurrent) {\n destination.next(value);\n try {\n const { project } = this;\n const result = project(value, index);\n if (!this.scheduler) {\n this.subscribeToProjection(result, value, index);\n } else {\n const state: DispatchArg = { subscriber: this, result, value, index };\n const destination = this.destination as Subscription;\n destination.add(this.scheduler.schedule>(ExpandSubscriber.dispatch, 0, state));\n }\n } catch (e) {\n destination.error(e);\n }\n } else {\n this.buffer.push(value);\n }\n }\n\n private subscribeToProjection(result: any, value: T, index: number): void {\n this.active++;\n const destination = this.destination as Subscription;\n destination.add(subscribeToResult(this, result, value, index));\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.hasCompleted && this.active === 0) {\n this.destination.complete();\n }\n this.unsubscribe();\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this._next(innerValue);\n }\n\n notifyComplete(innerSub: Subscription): void {\n const buffer = this.buffer;\n const destination = this.destination as Subscription;\n destination.remove(innerSub);\n this.active--;\n if (buffer && buffer.length > 0) {\n this._next(buffer.shift());\n }\n if (this.hasCompleted && this.active === 0) {\n this.destination.complete();\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable, but will call a specified function when\n * the source terminates on complete or error.\n * @param {function} callback Function to be called when source terminates.\n * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.\n * @method finally\n * @owner Observable\n */\nexport function finalize(callback: () => void): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new FinallyOperator(callback));\n}\n\nclass FinallyOperator implements Operator {\n constructor(private callback: () => void) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new FinallySubscriber(subscriber, this.callback));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FinallySubscriber extends Subscriber {\n constructor(destination: Subscriber, callback: () => void) {\n super(destination);\n this.add(new Subscription(callback));\n }\n}\n","import {Observable} from '../Observable';\nimport {Operator} from '../Operator';\nimport {Subscriber} from '../Subscriber';\nimport {OperatorFunction} from '../types';\n\nexport function find(predicate: (value: T, index: number, source: Observable) => value is S,\n thisArg?: any): OperatorFunction;\nexport function find(predicate: (value: T, index: number, source: Observable) => boolean,\n thisArg?: any): OperatorFunction;\n/**\n * Emits only the first value emitted by the source Observable that meets some\n * condition.\n *\n * Finds the first value that passes some test and emits\n * that.\n *\n * ![](find.png)\n *\n * `find` searches for the first item in the source Observable that matches the\n * specified condition embodied by the `predicate`, and returns the first\n * occurrence in the source. Unlike {@link first}, the `predicate` is required\n * in `find`, and does not emit an error if a valid value is not found.\n *\n * ## Example\n * Find and emit the first click that happens on a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { find } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(find(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link first}\n * @see {@link findIndex}\n * @see {@link take}\n *\n * @param {function(value: T, index: number, source: Observable): boolean} predicate\n * A function called with each item to test for condition matching.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of the first item that matches the\n * condition.\n * @method find\n * @owner Observable\n */\nexport function find(predicate: (value: T, index: number, source: Observable) => boolean,\n thisArg?: any): OperatorFunction {\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate is not a function');\n }\n return (source: Observable) => source.lift(new FindValueOperator(predicate, source, false, thisArg)) as Observable;\n}\n\nexport class FindValueOperator implements Operator {\n constructor(private predicate: (value: T, index: number, source: Observable) => boolean,\n private source: Observable,\n private yieldIndex: boolean,\n private thisArg?: any) {\n }\n\n call(observer: Subscriber, source: any): any {\n return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class FindValueSubscriber extends Subscriber {\n private index: number = 0;\n\n constructor(destination: Subscriber,\n private predicate: (value: T, index: number, source: Observable) => boolean,\n private source: Observable,\n private yieldIndex: boolean,\n private thisArg?: any) {\n super(destination);\n }\n\n private notifyComplete(value: any): void {\n const destination = this.destination;\n\n destination.next(value);\n destination.complete();\n this.unsubscribe();\n }\n\n protected _next(value: T): void {\n const {predicate, thisArg} = this;\n const index = this.index++;\n try {\n const result = predicate.call(thisArg || this, value, index, this.source);\n if (result) {\n this.notifyComplete(this.yieldIndex ? index : value);\n }\n } catch (err) {\n this.destination.error(err);\n }\n }\n\n protected _complete(): void {\n this.notifyComplete(this.yieldIndex ? -1 : undefined);\n }\n}\n","import { Observable } from '../Observable';\nimport { FindValueOperator } from '../operators/find';\nimport { OperatorFunction } from '../types';\n/**\n * Emits only the index of the first value emitted by the source Observable that\n * meets some condition.\n *\n * It's like {@link find}, but emits the index of the\n * found value, not the value itself.\n *\n * ![](findIndex.png)\n *\n * `findIndex` searches for the first item in the source Observable that matches\n * the specified condition embodied by the `predicate`, and returns the\n * (zero-based) index of the first occurrence in the source. Unlike\n * {@link first}, the `predicate` is required in `findIndex`, and does not emit\n * an error if a valid value is not found.\n *\n * ## Example\n * Emit the index of first click that happens on a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { findIndex } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(findIndex(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link first}\n * @see {@link take}\n *\n * @param {function(value: T, index: number, source: Observable): boolean} predicate\n * A function called with each item to test for condition matching.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of the index of the first item that\n * matches the condition.\n * @method find\n * @owner Observable\n */\nexport function findIndex(predicate: (value: T, index: number, source: Observable) => boolean,\n thisArg?: any): OperatorFunction {\n return (source: Observable) => source.lift(new FindValueOperator(predicate, source, true, thisArg)) as Observable;\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction } from '../../internal/types';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\n\n/* tslint:disable:max-line-length */\nexport function first(\n predicate?: null,\n defaultValue?: D\n): OperatorFunction;\nexport function first(\n predicate: (value: T, index: number, source: Observable) => value is S,\n defaultValue?: S\n): OperatorFunction;\nexport function first(\n predicate: (value: T, index: number, source: Observable) => boolean,\n defaultValue?: D\n): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Emits only the first value (or the first value that meets some condition)\n * emitted by the source Observable.\n *\n * Emits only the first value. Or emits only the first\n * value that passes some test.\n *\n * ![](first.png)\n *\n * If called with no arguments, `first` emits the first value of the source\n * Observable, then completes. If called with a `predicate` function, `first`\n * emits the first value of the source that matches the specified condition. It\n * may also take a deprecated `resultSelector` function to produce the output\n * value from the input value, and a `defaultValue` to emit in case the source\n * completes before it is able to emit a valid value. Throws an error if\n * `defaultValue` was not provided and a matching element is not found.\n *\n * ## Examples\n * Emit only the first click that happens on the DOM\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { first } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Emits the first click that happens on a DIV\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { first } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link take}\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n *\n * @param {function(value: T, index: number, source: Observable): boolean} [predicate]\n * An optional function called with each item to test for condition matching.\n * @param {R} [defaultValue] The default value emitted in case no valid value\n * was found on the source.\n * @return {Observable} An Observable of the first item that matches the\n * condition.\n * @method first\n * @owner Observable\n */\nexport function first(\n predicate?: ((value: T, index: number, source: Observable) => boolean) | null,\n defaultValue?: D\n): OperatorFunction {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable) => source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n take(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(() => new EmptyError()),\n );\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\n\n/**\n * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.\n *\n * ![](ignoreElements.png)\n *\n * ## Examples\n * ### Ignores emitted values, reacts to observable's completion.\n * ```ts\n * import { of } from 'rxjs';\n * import { ignoreElements } from 'rxjs/operators';\n *\n * of('you', 'talking', 'to', 'me').pipe(\n * ignoreElements(),\n * )\n * .subscribe(\n * word => console.log(word),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'the end'\n * ```\n * @return {Observable} An empty Observable that only calls `complete`\n * or `error`, based on which one is called by the source Observable.\n * @method ignoreElements\n * @owner Observable\n */\nexport function ignoreElements(): OperatorFunction {\n return function ignoreElementsOperatorFunction(source: Observable) {\n return source.lift(new IgnoreElementsOperator());\n };\n}\n\nclass IgnoreElementsOperator implements Operator {\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new IgnoreElementsSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass IgnoreElementsSubscriber extends Subscriber {\n protected _next(unused: T): void {\n // Do nothing\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Emits false if the input observable emits any values, or emits true if the\n * input observable completes without emitting any values.\n *\n * Tells whether any values are emitted by an observable\n *\n * ![](isEmpty.png)\n *\n * `isEmpty` transforms an Observable that emits values into an Observable that\n * emits a single boolean value representing whether or not any values were\n * emitted by the source Observable. As soon as the source Observable emits a\n * value, `isEmpty` will emit a `false` and complete. If the source Observable\n * completes having not emitted anything, `isEmpty` will emit a `true` and\n * complete.\n *\n * A similar effect could be achieved with {@link count}, but `isEmpty` can emit\n * a `false` value sooner.\n *\n * ## Examples\n *\n * Emit `false` for a non-empty Observable\n * ```javascript\n * import { Subject } from 'rxjs';\n * import { isEmpty } from 'rxjs/operators';\n *\n * const source = new Subject();\n * const result = source.pipe(isEmpty());\n * source.subscribe(x => console.log(x));\n * result.subscribe(x => console.log(x));\n * source.next('a');\n * source.next('b');\n * source.next('c');\n * source.complete();\n *\n * // Results in:\n * // a\n * // false\n * // b\n * // c\n * ```\n *\n * Emit `true` for an empty Observable\n * ```javascript\n * import { EMPTY } from 'rxjs';\n * import { isEmpty } from 'rxjs/operators';\n *\n * const result = EMPTY.pipe(isEmpty());\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // true\n * ```\n *\n * @see {@link count}\n * @see {@link EMPTY}\n *\n * @return {OperatorFunction} An Observable of a boolean value indicating whether observable was empty or not\n * @method isEmpty\n * @owner Observable\n */\n\nexport function isEmpty(): OperatorFunction {\n return (source: Observable) => source.lift(new IsEmptyOperator());\n}\n\nclass IsEmptyOperator implements Operator {\n call (observer: Subscriber, source: any): any {\n return source.subscribe(new IsEmptySubscriber(observer));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass IsEmptySubscriber extends Subscriber {\n constructor(destination: Subscriber) {\n super(destination);\n }\n\n private notifyComplete(isEmpty: boolean): void {\n const destination = this.destination;\n\n destination.next(isEmpty);\n destination.complete();\n }\n\n protected _next(value: boolean) {\n this.notifyComplete(false);\n }\n\n protected _complete() {\n this.notifyComplete(true);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the last `count` values emitted by the source Observable.\n *\n * Remembers the latest `count` values, then emits those\n * only when the source completes.\n *\n * ![](takeLast.png)\n *\n * `takeLast` returns an Observable that emits at most the last `count` values\n * emitted by the source Observable. If the source emits fewer than `count`\n * values then all of its values are emitted. This operator must wait until the\n * `complete` notification emission from the source in order to emit the `next`\n * values on the output Observable, because otherwise it is impossible to know\n * whether or not more values will be emitted on the source. For this reason,\n * all values are emitted synchronously, followed by the complete notification.\n *\n * ## Example\n * Take the last 3 values of an Observable with many values\n * ```ts\n * import { range } from 'rxjs';\n * import { takeLast } from 'rxjs/operators';\n *\n * const many = range(1, 100);\n * const lastThree = many.pipe(takeLast(3));\n * lastThree.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of values to emit from the end of\n * the sequence of values emitted by the source Observable.\n * @return {Observable} An Observable that emits at most the last count\n * values emitted by the source Observable.\n * @method takeLast\n * @owner Observable\n */\nexport function takeLast(count: number): MonoTypeOperatorFunction {\n return function takeLastOperatorFunction(source: Observable): Observable {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeLastOperator(count));\n }\n };\n}\n\nclass TakeLastOperator implements Operator {\n constructor(private total: number) {\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError;\n }\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new TakeLastSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeLastSubscriber extends Subscriber {\n private ring: Array = new Array();\n private count: number = 0;\n\n constructor(destination: Subscriber, private total: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const ring = this.ring;\n const total = this.total;\n const count = this.count++;\n\n if (ring.length < total) {\n ring.push(value);\n } else {\n const index = count % total;\n ring[index] = value;\n }\n }\n\n protected _complete(): void {\n const destination = this.destination;\n let count = this.count;\n\n if (count > 0) {\n const total = this.count >= this.total ? this.total : this.count;\n const ring = this.ring;\n\n for (let i = 0; i < total; i++) {\n const idx = (count++) % total;\n destination.next(ring[idx]);\n }\n }\n\n destination.complete();\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction } from '../../internal/types';\nimport { filter } from './filter';\nimport { takeLast } from './takeLast';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { identity } from '../util/identity';\n\n/* tslint:disable:max-line-length */\nexport function last(\n predicate?: null,\n defaultValue?: D\n): OperatorFunction;\nexport function last(\n predicate: (value: T, index: number, source: Observable) => value is S,\n defaultValue?: S\n): OperatorFunction;\nexport function last(\n predicate: (value: T, index: number, source: Observable) => boolean,\n defaultValue?: D\n): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits only the last item emitted by the source Observable.\n * It optionally takes a predicate function as a parameter, in which case, rather than emitting\n * the last item from the source Observable, the resulting Observable will emit the last item\n * from the source Observable that satisfies the predicate.\n *\n * ![](last.png)\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @param {function} [predicate] - The condition any source emitted item has to satisfy.\n * @param {any} [defaultValue] - An optional default value to provide if last\n * predicate isn't met or no values were emitted.\n * @return {Observable} An Observable that emits only the last item satisfying the given condition\n * from the source, or an NoSuchElementException if no such items are emitted.\n * @throws - Throws if no items that match the predicate are emitted by the source Observable.\n */\nexport function last(\n predicate?: ((value: T, index: number, source: Observable) => boolean) | null,\n defaultValue?: D\n): OperatorFunction {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable) => source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n takeLast(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(() => new EmptyError()),\n );\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Emits the given constant value on the output Observable every time the source\n * Observable emits a value.\n *\n * Like {@link map}, but it maps every source value to\n * the same output value every time.\n *\n * ![](mapTo.png)\n *\n * Takes a constant `value` as argument, and emits that whenever the source\n * Observable emits a value. In other words, ignores the actual source value,\n * and simply uses the emission moment to know when to emit the given `value`.\n *\n * ## Example\n * Map every click to the string 'Hi'\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { mapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const greetings = clicks.pipe(mapTo('Hi'));\n * greetings.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param {any} value The value to map each source value to.\n * @return {Observable} An Observable that emits the given `value` every time\n * the source Observable emits something.\n * @method mapTo\n * @owner Observable\n */\nexport function mapTo(value: R): OperatorFunction {\n return (source: Observable) => source.lift(new MapToOperator(value));\n}\n\nclass MapToOperator implements Operator {\n\n value: R;\n\n constructor(value: R) {\n this.value = value;\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new MapToSubscriber(subscriber, this.value));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapToSubscriber extends Subscriber {\n\n value: R;\n\n constructor(destination: Subscriber, value: R) {\n super(destination);\n this.value = value;\n }\n\n protected _next(x: T) {\n this.destination.next(this.value);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nimport { OperatorFunction } from '../types';\n\n/**\n * Represents all of the notifications from the source Observable as `next`\n * emissions marked with their original types within {@link Notification}\n * objects.\n *\n * Wraps `next`, `error` and `complete` emissions in\n * {@link Notification} objects, emitted as `next` on the output Observable.\n * \n *\n * ![](materialize.png)\n *\n * `materialize` returns an Observable that emits a `next` notification for each\n * `next`, `error`, or `complete` emission of the source Observable. When the\n * source Observable emits `complete`, the output Observable will emit `next` as\n * a Notification of type \"complete\", and then it will emit `complete` as well.\n * When the source Observable emits `error`, the output will emit `next` as a\n * Notification of type \"error\", and then `complete`.\n *\n * This operator is useful for producing metadata of the source Observable, to\n * be consumed as `next` emissions. Use it in conjunction with\n * {@link dematerialize}.\n *\n * ## Example\n * Convert a faulty Observable to an Observable of Notifications\n * ```ts\n * import { of } from 'rxjs';\n * import { materialize, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 13, 'd');\n * const upperCase = letters.pipe(map(x => x.toUpperCase()));\n * const materialized = upperCase.pipe(materialize());\n * materialized.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - Notification {kind: \"N\", value: \"A\", error: undefined, hasValue: true}\n * // - Notification {kind: \"N\", value: \"B\", error: undefined, hasValue: true}\n * // - Notification {kind: \"E\", value: undefined, error: TypeError:\n * // x.toUpperCase is not a function at MapSubscriber.letters.map.x\n * // [as project] (http://1…, hasValue: false}\n * ```\n *\n * @see {@link Notification}\n * @see {@link dematerialize}\n *\n * @return {Observable>} An Observable that emits\n * {@link Notification} objects that wrap the original emissions from the source\n * Observable with metadata.\n * @method materialize\n * @owner Observable\n */\nexport function materialize(): OperatorFunction> {\n return function materializeOperatorFunction(source: Observable) {\n return source.lift(new MaterializeOperator());\n };\n}\n\nclass MaterializeOperator implements Operator> {\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new MaterializeSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MaterializeSubscriber extends Subscriber {\n constructor(destination: Subscriber>) {\n super(destination);\n }\n\n protected _next(value: T) {\n this.destination.next(Notification.createNext(value));\n }\n\n protected _error(err: any) {\n const destination = this.destination;\n destination.next(Notification.createError(err));\n destination.complete();\n }\n\n protected _complete() {\n const destination = this.destination;\n destination.next(Notification.createComplete());\n destination.complete();\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function scan(accumulator: (acc: R, value: T, index: number) => R, seed: R): OperatorFunction;\nexport function scan(accumulator: (acc: T, value: T, index: number) => T, seed?: T): MonoTypeOperatorFunction;\nexport function scan(accumulator: (acc: R, value: T, index: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Applies an accumulator function over the source Observable, and returns each\n * intermediate result, with an optional seed value.\n *\n * It's like {@link reduce}, but emits the current\n * accumulation whenever the source emits a value.\n *\n * ![](scan.png)\n *\n * Combines together all values emitted on the source, using an accumulator\n * function that knows how to join a new source value into the accumulation from\n * the past. Is similar to {@link reduce}, but emits the intermediate\n * accumulations.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n * Count the number of click events\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { scan, mapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const ones = clicks.pipe(mapTo(1));\n * const seed = 0;\n * const count = ones.pipe(scan((acc, one) => acc + one, seed));\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link reduce}\n *\n * @param {function(acc: R, value: T, index: number): R} accumulator\n * The accumulator function called on each source value.\n * @param {T|R} [seed] The initial accumulation value.\n * @return {Observable} An observable of the accumulated values.\n * @method scan\n * @owner Observable\n */\nexport function scan(accumulator: (acc: R, value: T, index: number) => R, seed?: T | R): OperatorFunction {\n let hasSeed = false;\n // providing a seed of `undefined` *should* be valid and trigger\n // hasSeed! so don't use `seed !== undefined` checks!\n // For this reason, we have to check it here at the original call site\n // otherwise inside Operator/Subscriber we won't know if `undefined`\n // means they didn't provide anything or if they literally provided `undefined`\n if (arguments.length >= 2) {\n hasSeed = true;\n }\n\n return function scanOperatorFunction(source: Observable): Observable {\n return source.lift(new ScanOperator(accumulator, seed, hasSeed));\n };\n}\n\nclass ScanOperator implements Operator {\n constructor(private accumulator: (acc: R, value: T, index: number) => R, private seed?: T | R, private hasSeed: boolean = false) {}\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ScanSubscriber extends Subscriber {\n private index: number = 0;\n\n get seed(): T | R {\n return this._seed;\n }\n\n set seed(value: T | R) {\n this.hasSeed = true;\n this._seed = value;\n }\n\n constructor(destination: Subscriber, private accumulator: (acc: R, value: T, index: number) => R, private _seed: T | R,\n private hasSeed: boolean) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (!this.hasSeed) {\n this.seed = value;\n this.destination.next(value);\n } else {\n return this._tryNext(value);\n }\n }\n\n private _tryNext(value: T): void {\n const index = this.index++;\n let result: any;\n try {\n result = this.accumulator(this.seed, value, index);\n } catch (err) {\n this.destination.error(err);\n }\n this.seed = result;\n this.destination.next(result);\n }\n}\n","import { Observable } from '../Observable';\nimport { scan } from './scan';\nimport { takeLast } from './takeLast';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { OperatorFunction, MonoTypeOperatorFunction } from '../types';\nimport { pipe } from '../util/pipe';\n\n/* tslint:disable:max-line-length */\nexport function reduce(accumulator: (acc: R, value: T, index: number) => R, seed: R): OperatorFunction;\nexport function reduce(accumulator: (acc: T, value: T, index: number) => T, seed?: T): MonoTypeOperatorFunction;\nexport function reduce(accumulator: (acc: R, value: T, index: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Applies an accumulator function over the source Observable, and returns the\n * accumulated result when the source completes, given an optional seed value.\n *\n * Combines together all values emitted on the source,\n * using an accumulator function that knows how to join a new source value into\n * the accumulation from the past.\n *\n * ![](reduce.png)\n *\n * Like\n * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),\n * `reduce` applies an `accumulator` function against an accumulation and each\n * value of the source Observable (from the past) to reduce it to a single\n * value, emitted on the output Observable. Note that `reduce` will only emit\n * one value, only when the source Observable completes. It is equivalent to\n * applying operator {@link scan} followed by operator {@link last}.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n * Count the number of click events that happened in 5 seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { reduce, takeUntil, mapTo } from 'rxjs/operators';\n *\n * const clicksInFiveSeconds = fromEvent(document, 'click').pipe(\n * takeUntil(interval(5000)),\n * );\n * const ones = clicksInFiveSeconds.pipe(mapTo(1));\n * const seed = 0;\n * const count = ones.pipe(reduce((acc, one) => acc + one, seed));\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link count}\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link scan}\n *\n * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function\n * called on each source value.\n * @param {R} [seed] The initial accumulation value.\n * @return {Observable} An Observable that emits a single value that is the\n * result of accumulating the values emitted by the source Observable.\n * @method reduce\n * @owner Observable\n */\nexport function reduce(accumulator: (acc: T | R, value: T, index?: number) => T | R, seed?: T | R): OperatorFunction {\n // providing a seed of `undefined` *should* be valid and trigger\n // hasSeed! so don't use `seed !== undefined` checks!\n // For this reason, we have to check it here at the original call site\n // otherwise inside Operator/Subscriber we won't know if `undefined`\n // means they didn't provide anything or if they literally provided `undefined`\n if (arguments.length >= 2) {\n return function reduceOperatorFunctionWithSeed(source: Observable): Observable {\n return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source);\n };\n }\n return function reduceOperatorFunction(source: Observable): Observable {\n return pipe(\n scan((acc, value, index) => accumulator(acc, value, index + 1)),\n takeLast(1),\n )(source);\n };\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/**\n * The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),\n * and when source Observable completes it emits a single item: the item with the largest value.\n *\n * ![](max.png)\n *\n * ## Examples\n * Get the maximal value of a series of numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { max } from 'rxjs/operators';\n *\n * of(5, 4, 7, 2, 8).pipe(\n * max(),\n * )\n * .subscribe(x => console.log(x)); // -> 8\n * ```\n *\n * Use a comparer function to get the maximal item\n * ```typescript\n * import { of } from 'rxjs';\n * import { max } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n * of(\n * {age: 7, name: 'Foo'},\n * {age: 5, name: 'Bar'},\n * {age: 9, name: 'Beer'},\n * ).pipe(\n * max((a: Person, b: Person) => a.age < b.age ? -1 : 1),\n * )\n * .subscribe((x: Person) => console.log(x.name)); // -> 'Beer'\n * ```\n *\n * @see {@link min}\n *\n * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the\n * value of two items.\n * @return {Observable} An Observable that emits item with the largest value.\n * @method max\n * @owner Observable\n */\nexport function max(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction {\n const max: (x: T, y: T) => T = (typeof comparer === 'function')\n ? (x, y) => comparer(x, y) > 0 ? x : y\n : (x, y) => x > y ? x : y;\n\n return reduce(max);\n}\n","import { merge as mergeStatic } from '../observable/merge';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(scheduler?: SchedulerLike): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(...observables: Array | SchedulerLike | number>): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static merge. */\nexport function merge(...observables: Array | SchedulerLike | number>): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link merge}.\n */\nexport function merge(...observables: Array | SchedulerLike | number>): OperatorFunction {\n return (source: Observable) => source.lift.call(mergeStatic(source, ...observables));\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction, ObservedValueOf } from '../../internal/types';\nimport { mergeMap } from './mergeMap';\nimport { ObservableInput } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function mergeMapTo>(innerObservable: O, concurrent?: number): OperatorFunction>;\n/** @deprecated */\nexport function mergeMapTo>(innerObservable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in the output Observable.\n *\n * It's like {@link mergeMap}, but maps each value always\n * to the same inner Observable.\n *\n * ![](mergeMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then merges those resulting Observables into one\n * single Observable, which is the output Observable.\n *\n * ## Example\n * For each click event, start an interval Observable ticking every 1 second\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { mergeMapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(mergeMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n * @see {@link switchMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits items from the given\n * `innerObservable`\n * @method mergeMapTo\n * @owner Observable\n */\nexport function mergeMapTo>(\n innerObservable: O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction|R> {\n if (typeof resultSelector === 'function') {\n return mergeMap(() => innerObservable, resultSelector, concurrent);\n }\n if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return mergeMap(() => innerObservable, concurrent);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { ObservableInput, OperatorFunction } from '../types';\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, then each intermediate\n * Observable returned is merged into the output Observable.\n *\n * It's like {@link scan}, but the Observables returned\n * by the accumulator are merged into the outer Observable.\n *\n * ## Example\n * Count the number of click events\n * ```ts\n * import { fromEvent, of } from 'rxjs';\n * import { mapTo, mergeScan } from 'rxjs/operators';\n *\n * const click$ = fromEvent(document, 'click');\n * const one$ = click$.pipe(mapTo(1));\n * const seed = 0;\n * const count$ = one$.pipe(\n * mergeScan((acc, one) => of(acc + one), seed),\n * );\n * count$.subscribe(x => console.log(x));\n *\n * // Results:\n * // 1\n * // 2\n * // 3\n * // 4\n * // ...and so on for each click\n * ```\n *\n * @param {function(acc: R, value: T): Observable} accumulator\n * The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of\n * input Observables being subscribed to concurrently.\n * @return {Observable} An observable of the accumulated values.\n * @method mergeScan\n * @owner Observable\n */\nexport function mergeScan(accumulator: (acc: R, value: T, index: number) => ObservableInput,\n seed: R,\n concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction {\n return (source: Observable) => source.lift(new MergeScanOperator(accumulator, seed, concurrent));\n}\n\nexport class MergeScanOperator implements Operator {\n constructor(private accumulator: (acc: R, value: T, index: number) => ObservableInput,\n private seed: R,\n private concurrent: number) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new MergeScanSubscriber(\n subscriber, this.accumulator, this.seed, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeScanSubscriber extends OuterSubscriber {\n private hasValue: boolean = false;\n private hasCompleted: boolean = false;\n private buffer: Observable[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber,\n private accumulator: (acc: R, value: T, index: number) => ObservableInput,\n private acc: R,\n private concurrent: number) {\n super(destination);\n }\n\n protected _next(value: any): void {\n if (this.active < this.concurrent) {\n const index = this.index++;\n const destination = this.destination;\n let ish;\n try {\n const { accumulator } = this;\n ish = accumulator(this.acc, value, index);\n } catch (e) {\n return destination.error(e);\n }\n this.active++;\n this._innerSub(ish, value, index);\n } else {\n this.buffer.push(value);\n }\n }\n\n private _innerSub(ish: any, value: T, index: number): void {\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n subscribeToResult(this, ish, value, index, innerSubscriber);\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n if (this.hasValue === false) {\n this.destination.next(this.acc);\n }\n this.destination.complete();\n }\n this.unsubscribe();\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n const { destination } = this;\n this.acc = innerValue;\n this.hasValue = true;\n destination.next(innerValue);\n }\n\n notifyComplete(innerSub: Subscription): void {\n const buffer = this.buffer;\n const destination = this.destination as Subscription;\n destination.remove(innerSub);\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift());\n } else if (this.active === 0 && this.hasCompleted) {\n if (this.hasValue === false) {\n this.destination.next(this.acc);\n }\n this.destination.complete();\n }\n }\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\n\n/**\n * The Min operator operates on an Observable that emits numbers (or items that can be compared with a provided function),\n * and when source Observable completes it emits a single item: the item with the smallest value.\n *\n * ![](min.png)\n *\n * ## Examples\n * Get the minimal value of a series of numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { min } from 'rxjs/operators';\n *\n * of(5, 4, 7, 2, 8).pipe(\n * min(),\n * )\n * .subscribe(x => console.log(x)); // -> 2\n * ```\n *\n * Use a comparer function to get the minimal item\n * ```typescript\n * import { of } from 'rxjs';\n * import { min } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n * of(\n * {age: 7, name: 'Foo'},\n * {age: 5, name: 'Bar'},\n * {age: 9, name: 'Beer'},\n * ).pipe(\n * min( (a: Person, b: Person) => a.age < b.age ? -1 : 1),\n * )\n * .subscribe((x: Person) => console.log(x.name)); // -> 'Bar'\n * ```\n * @see {@link max}\n *\n * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the\n * value of two items.\n * @return {Observable} An Observable that emits item with the smallest value.\n * @method min\n * @owner Observable\n */\nexport function min(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction {\n const min: (x: T, y: T) => T = (typeof comparer === 'function')\n ? (x, y) => comparer(x, y) < 0 ? x : y\n : (x, y) => x < y ? x : y;\n return reduce(min);\n}\n","import { Subject } from '../Subject';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { ConnectableObservable, connectableObservableDescriptor } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservedValueOf, ObservableInput } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function multicast(subject: Subject): UnaryFunction, ConnectableObservable>;\nexport function multicast>(subject: Subject, selector: (shared: Observable) => O): UnaryFunction, ConnectableObservable>>;\nexport function multicast(subjectFactory: (this: Observable) => Subject): UnaryFunction, ConnectableObservable>;\nexport function multicast>(SubjectFactory: (this: Observable) => Subject, selector: (shared: Observable) => O): OperatorFunction>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the results of invoking a specified selector on items\n * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.\n *\n * ![](multicast.png)\n *\n * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through\n * which the source sequence's elements will be multicast to the selector function\n * or Subject to push source elements into.\n * @param {Function} [selector] - Optional selector function that can use the multicasted source stream\n * as many times as needed, without causing multiple subscriptions to the source stream.\n * Subscribers to the given source will receive all notifications of the source from the\n * time of the subscription forward.\n * @return {Observable} An Observable that emits the results of invoking the selector\n * on the items emitted by a `ConnectableObservable` that shares a single subscription to\n * the underlying stream.\n * @method multicast\n * @owner Observable\n */\nexport function multicast(subjectOrSubjectFactory: Subject | (() => Subject),\n selector?: (source: Observable) => Observable): OperatorFunction {\n return function multicastOperatorFunction(source: Observable): Observable {\n let subjectFactory: () => Subject;\n if (typeof subjectOrSubjectFactory === 'function') {\n subjectFactory = <() => Subject>subjectOrSubjectFactory;\n } else {\n subjectFactory = function subjectFactory() {\n return >subjectOrSubjectFactory;\n };\n }\n\n if (typeof selector === 'function') {\n return source.lift(new MulticastOperator(subjectFactory, selector));\n }\n\n const connectable: any = Object.create(source, connectableObservableDescriptor);\n connectable.source = source;\n connectable.subjectFactory = subjectFactory;\n\n return > connectable;\n };\n}\n\nexport class MulticastOperator implements Operator {\n constructor(private subjectFactory: () => Subject,\n private selector: (source: Observable) => Observable) {\n }\n call(subscriber: Subscriber, source: any): any {\n const { selector } = this;\n const subject = this.subjectFactory();\n const subscription = selector(subject).subscribe(subscriber);\n subscription.add(source.subscribe(subject));\n return subscription;\n }\n}\n","import { Observable } from '../Observable';\nimport { from } from '../observable/from';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { isArray } from '../util/isArray';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNext(): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput, v2: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput, v2: ObservableInput, v3: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(v: ObservableInput, v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): OperatorFunction;\nexport function onErrorResumeNext(...observables: Array>): OperatorFunction;\nexport function onErrorResumeNext(array: ObservableInput[]): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * Execute series of Observables no matter what, even if it means swallowing errors.\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as\n * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same\n * as the source.\n *\n * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.\n * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`\n * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting\n * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another\n * Observable in provided series, no matter if previous Observable completed or ended with an error. This will\n * be happening until there is no more Observables left in the series, at which point returned Observable will\n * complete - even if the last subscribed stream ended with an error.\n *\n * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive\n * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable\n * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with\n * an error.\n *\n * Note that you do not get any access to errors emitted by the Observables. In particular do not\n * expect these errors to appear in error callback passed to {@link Observable#subscribe}. If you want to take\n * specific actions based on what error was emitted by an Observable, you should try out {@link catchError} instead.\n *\n *\n * ## Example\n * Subscribe to the next Observable after map fails\n * ```ts\n * import { of } from 'rxjs';\n * import { onErrorResumeNext, map } from 'rxjs/operators';\n *\n * of(1, 2, 3, 0).pipe(\n * map(x => {\n * if (x === 0) { throw Error(); }\n * return 10 / x;\n * }),\n * onErrorResumeNext(of(1, 2, 3)),\n * )\n * .subscribe(\n * val => console.log(val),\n * err => console.log(err), // Will never be called.\n * () => console.log('that\\'s it!')\n * );\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // \"that's it!\"\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param {...ObservableInput} observables Observables passed either directly or as an array.\n * @return {Observable} An Observable that emits values from source Observable, but - if it errors - subscribes\n * to the next passed Observable and so on, until it completes or runs out of Observables.\n * @method onErrorResumeNext\n * @owner Observable\n */\n\nexport function onErrorResumeNext(...nextSources: Array |\n Array>>): OperatorFunction {\n if (nextSources.length === 1 && isArray(nextSources[0])) {\n nextSources = >>nextSources[0];\n }\n\n return (source: Observable) => source.lift(new OnErrorResumeNextOperator(nextSources));\n}\n\n/* tslint:disable:max-line-length */\nexport function onErrorResumeNextStatic(v: ObservableInput): Observable;\nexport function onErrorResumeNextStatic(v2: ObservableInput, v3: ObservableInput): Observable;\nexport function onErrorResumeNextStatic(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): Observable;\nexport function onErrorResumeNextStatic(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): Observable;\nexport function onErrorResumeNextStatic(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): Observable;\n\nexport function onErrorResumeNextStatic(...observables: Array | ((...values: Array) => R)>): Observable;\nexport function onErrorResumeNextStatic(array: ObservableInput[]): Observable;\n/* tslint:enable:max-line-length */\n\nexport function onErrorResumeNextStatic(...nextSources: Array |\n Array> |\n ((...values: Array) => R)>): Observable {\n let source: ObservableInput = null;\n\n if (nextSources.length === 1 && isArray(nextSources[0])) {\n nextSources = >>nextSources[0];\n }\n source = nextSources.shift();\n\n return from(source, null).lift(new OnErrorResumeNextOperator(nextSources));\n}\n\nclass OnErrorResumeNextOperator implements Operator {\n constructor(private nextSources: Array>) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));\n }\n}\n\nclass OnErrorResumeNextSubscriber extends OuterSubscriber {\n constructor(protected destination: Subscriber,\n private nextSources: Array>) {\n super(destination);\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this.subscribeToNextSource();\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n this.subscribeToNextSource();\n }\n\n protected _error(err: any): void {\n this.subscribeToNextSource();\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.subscribeToNextSource();\n this.unsubscribe();\n }\n\n private subscribeToNextSource(): void {\n const next = this.nextSources.shift();\n if (!!next) {\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n subscribeToResult(this, next, undefined, undefined, innerSubscriber);\n } else {\n this.destination.complete();\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\n\n/**\n * Groups pairs of consecutive emissions together and emits them as an array of\n * two values.\n *\n * Puts the current value and previous value together as\n * an array, and emits that.\n *\n * ![](pairwise.png)\n *\n * The Nth emission from the source Observable will cause the output Observable\n * to emit an array [(N-1)th, Nth] of the previous and the current value, as a\n * pair. For this reason, `pairwise` emits on the second and subsequent\n * emissions from the source Observable, but not on the first emission, because\n * there is no previous value in that case.\n *\n * ## Example\n * On every click (starting from the second), emit the relative distance to the previous click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { pairwise, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const pairs = clicks.pipe(pairwise());\n * const distance = pairs.pipe(\n * map(pair => {\n * const x0 = pair[0].clientX;\n * const y0 = pair[0].clientY;\n * const x1 = pair[1].clientX;\n * const y1 = pair[1].clientY;\n * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));\n * }),\n * );\n * distance.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n *\n * @return {Observable>} An Observable of pairs (as arrays) of\n * consecutive values from the source Observable.\n * @method pairwise\n * @owner Observable\n */\nexport function pairwise(): OperatorFunction {\n return (source: Observable) => source.lift(new PairwiseOperator());\n}\n\nclass PairwiseOperator implements Operator {\n call(subscriber: Subscriber<[T, T]>, source: any): any {\n return source.subscribe(new PairwiseSubscriber(subscriber));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass PairwiseSubscriber extends Subscriber {\n private prev: T;\n private hasPrev: boolean = false;\n\n constructor(destination: Subscriber<[T, T]>) {\n super(destination);\n }\n\n _next(value: T): void {\n let pair: [T, T] | undefined;\n\n if (this.hasPrev) {\n pair = [this.prev, value];\n } else {\n this.hasPrev = true;\n }\n\n this.prev = value;\n\n if (pair) {\n this.destination.next(pair);\n }\n }\n}\n","import { not } from '../util/not';\nimport { filter } from './filter';\nimport { Observable } from '../Observable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.\n *\n * ![](partition.png)\n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n * Partition click events into those on DIV elements and those elsewhere\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { partition } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const parts = clicks.pipe(partition(ev => ev.target.tagName === 'DIV'));\n * const clicksOnDivs = parts[0];\n * const clicksElsewhere = parts[1];\n * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x));\n * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x));\n * ```\n *\n * @see {@link filter}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted on the first Observable in the returned array, if\n * `false` the value is emitted on the second Observable in the array. The\n * `index` parameter is the number `i` for the i-th source emission that has\n * happened since the subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {[Observable, Observable]} An array with two Observables: one\n * with values that passed the predicate, and another with values that did not\n * pass the predicate.\n * @method partition\n * @owner Observable\n */\n/**\n * @deprecated use `partition` static creation function instead\n */\nexport function partition(predicate: (value: T, index: number) => boolean,\n thisArg?: any): UnaryFunction, [Observable, Observable]> {\n return (source: Observable) => [\n filter(predicate, thisArg)(source),\n filter(not(predicate, thisArg) as any)(source)\n ] as [Observable, Observable];\n}\n","import { Observable } from '../Observable';\nimport { map } from './map';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pluck(k1: K1): OperatorFunction;\nexport function pluck(k1: K1, k2: K2): OperatorFunction;\nexport function pluck(k1: K1, k2: K2, k3: K3): OperatorFunction;\nexport function pluck(k1: K1, k2: K2, k3: K3, k4: K4): OperatorFunction;\nexport function pluck(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): OperatorFunction;\nexport function pluck(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6): OperatorFunction;\nexport function pluck(...properties: string[]): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Maps each source value (an object) to its specified nested property.\n *\n * Like {@link map}, but meant only for picking one of\n * the nested properties of every emitted object.\n *\n * ![](pluck.png)\n *\n * Given a list of strings describing a path to an object property, retrieves\n * the value of a specified nested property from all values in the source\n * Observable. If a property can't be resolved, it will return `undefined` for\n * that value.\n *\n * ## Example\n * Map every click to the tagName of the clicked target element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { pluck } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const tagNames = clicks.pipe(pluck('target', 'tagName'));\n * tagNames.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param {...string} properties The nested properties to pluck from each source\n * value (an object).\n * @return {Observable} A new Observable of property values from the source values.\n * @method pluck\n * @owner Observable\n */\nexport function pluck(...properties: string[]): OperatorFunction {\n const length = properties.length;\n if (length === 0) {\n throw new Error('list of properties cannot be empty.');\n }\n return (source: Observable) => map(plucker(properties, length))(source as any);\n}\n\nfunction plucker(props: string[], length: number): (x: string) => any {\n const mapper = (x: string) => {\n let currentProp = x;\n for (let i = 0; i < length; i++) {\n const p = currentProp[props[i]];\n if (typeof p !== 'undefined') {\n currentProp = p;\n } else {\n return undefined;\n }\n }\n return currentProp;\n };\n\n return mapper;\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function publish(): UnaryFunction, ConnectableObservable>;\nexport function publish>(selector: (shared: Observable) => O): OperatorFunction>;\nexport function publish(selector: MonoTypeOperatorFunction): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called\n * before it begins emitting items to those Observers that have subscribed to it.\n *\n * Makes a cold Observable hot\n *\n * ![](publish.png)\n *\n * ## Examples\n * Make source$ hot by applying publish operator, then merge each inner observable into a single one\n * and subscribe.\n * ```ts\n * import { of, zip, interval, merge } from \"rxjs\";\n * import { map, publish, tap } from \"rxjs/operators\";\n *\n * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9)).pipe(\n * map(values => values[1])\n * );\n *\n * source$\n * .pipe(\n * publish(multicasted$ =>\n * merge(\n * multicasted$.pipe(tap(x => console.log('Stream 1:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 2:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 3:', x))),\n * )\n * )\n * )\n * .subscribe();\n *\n * // Results every two seconds\n * // Stream 1: 1\n * // Stream 2: 1\n * // Stream 3: 1\n * // ...\n * // Stream 1: 9\n * // Stream 2: 9\n * // Stream 3: 9\n * ```\n *\n * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times\n * as needed, without causing multiple subscriptions to the source sequence.\n * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.\n * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.\n * @method publish\n * @owner Observable\n *\n *\n */\nexport function publish(selector?: OperatorFunction): MonoTypeOperatorFunction | OperatorFunction {\n return selector ?\n multicast(() => new Subject(), selector) :\n multicast(new Subject());\n}\n","import { Observable } from '../Observable';\nimport { BehaviorSubject } from '../BehaviorSubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * @param value\n * @return {ConnectableObservable}\n * @method publishBehavior\n * @owner Observable\n */\nexport function publishBehavior(value: T): UnaryFunction, ConnectableObservable> {\n return (source: Observable) => multicast(new BehaviorSubject(value))(source) as ConnectableObservable;\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Returns a connectable observable sequence that shares a single subscription to the\n * underlying sequence containing only the last notification.\n *\n * ![](publishLast.png)\n *\n * Similar to {@link publish}, but it waits until the source observable completes and stores\n * the last emitted value.\n * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last\n * value even if it has no more subscribers. If subsequent subscriptions happen, they will\n * immediately get that last stored value and complete.\n *\n * ## Example\n *\n * ```ts\n * import { interval } from 'rxjs';\n * import { publishLast, tap, take } from 'rxjs/operators';\n *\n * const connectable =\n * interval(1000)\n * .pipe(\n * tap(x => console.log(\"side effect\", x)),\n * take(3),\n * publishLast());\n *\n * connectable.subscribe(\n * x => console.log( \"Sub. A\", x),\n * err => console.log(\"Sub. A Error\", err),\n * () => console.log( \"Sub. A Complete\"));\n *\n * connectable.subscribe(\n * x => console.log( \"Sub. B\", x),\n * err => console.log(\"Sub. B Error\", err),\n * () => console.log( \"Sub. B Complete\"));\n *\n * connectable.connect();\n *\n * // Results:\n * // \"side effect 0\"\n * // \"side effect 1\"\n * // \"side effect 2\"\n * // \"Sub. A 2\"\n * // \"Sub. B 2\"\n * // \"Sub. A Complete\"\n * // \"Sub. B Complete\"\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link publish}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @return {ConnectableObservable} An observable sequence that contains the elements of a\n * sequence produced by multicasting the source sequence.\n * @method publishLast\n * @owner Observable\n */\n\nexport function publishLast(): UnaryFunction, ConnectableObservable> {\n return (source: Observable) => multicast(new AsyncSubject())(source);\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction, MonoTypeOperatorFunction, OperatorFunction, SchedulerLike, ObservableInput, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function publishReplay(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction;\nexport function publishReplay>(bufferSize?: number, windowTime?: number, selector?: (shared: Observable) => O, scheduler?: SchedulerLike): OperatorFunction>;\n/* tslint:enable:max-line-length */\n\nexport function publishReplay(bufferSize?: number,\n windowTime?: number,\n selectorOrScheduler?: SchedulerLike | OperatorFunction,\n scheduler?: SchedulerLike): UnaryFunction, ConnectableObservable> {\n\n if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {\n scheduler = selectorOrScheduler;\n }\n\n const selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;\n const subject = new ReplaySubject(bufferSize, windowTime, scheduler);\n\n return (source: Observable) => multicast(() => subject, selector)(source) as ConnectableObservable;\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { MonoTypeOperatorFunction, OperatorFunction } from '../types';\nimport { race as raceStatic } from '../observable/race';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static race. */\nexport function race(observables: Array>): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static race. */\nexport function race(observables: Array>): OperatorFunction;\n/** @deprecated Deprecated in favor of static race. */\nexport function race(...observables: Array | Array>>): MonoTypeOperatorFunction;\n/** @deprecated Deprecated in favor of static race. */\nexport function race(...observables: Array | Array>>): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that mirrors the first source Observable to emit a next,\n * error or complete notification from the combination of this Observable and supplied Observables.\n * @param {...Observables} ...observables Sources used to race for which Observable emits first.\n * @return {Observable} An Observable that mirrors the output of the first Observable to emit an item.\n * @method race\n * @owner Observable\n * @deprecated Deprecated in favor of static {@link race}.\n */\nexport function race(...observables: (Observable | Observable[])[]): MonoTypeOperatorFunction {\n return function raceOperatorFunction(source: Observable) {\n // if the only argument is an array, it was most likely called with\n // `pair([obs1, obs2, ...])`\n if (observables.length === 1 && isArray(observables[0])) {\n observables = observables[0] as Observable[];\n }\n\n return source.lift.call(raceStatic(source, ...(observables as Observable[])));\n };\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { empty } from '../observable/empty';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that will resubscribe to the source stream when the source stream completes, at most count times.\n *\n * Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.\n *\n * ![](repeat.png)\n *\n * Similar to {@link retry}, this operator repeats the stream of items emitted by the source for non error cases.\n * Repeat can be useful for creating observables that are meant to have some repeated pattern or rhythm.\n *\n * Note: `repeat(0)` returns an empty observable and `repeat()` will repeat forever\n *\n * ## Example\n * Repeat a message stream\n * ```ts\n * import { of } from 'rxjs';\n * import { repeat, delay } from 'rxjs/operators';\n *\n * const source = of('Repeat message');\n * const example = source.pipe(repeat(3));\n * example.subscribe(x => console.log(x));\n *\n * // Results\n * // Repeat message\n * // Repeat message\n * // Repeat message\n * ```\n *\n * Repeat 3 values, 2 times\n * ```ts\n * import { interval } from 'rxjs';\n * import { repeat, take } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const example = source.pipe(take(3), repeat(2));\n * example.subscribe(x => console.log(x));\n *\n * // Results every second\n * // 0\n * // 1\n * // 2\n * // 0\n * // 1\n * // 2\n * ```\n *\n * @see {@link repeatWhen}\n * @see {@link retry}\n *\n * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield\n * an empty Observable.\n * @return {Observable} An Observable that will resubscribe to the source stream when the source stream completes\n * , at most count times.\n * @method repeat\n * @owner Observable\n */\nexport function repeat(count: number = -1): MonoTypeOperatorFunction {\n return (source: Observable) => {\n if (count === 0) {\n return empty();\n } else if (count < 0) {\n return source.lift(new RepeatOperator(-1, source));\n } else {\n return source.lift(new RepeatOperator(count - 1, source));\n }\n };\n}\n\nclass RepeatOperator implements Operator {\n constructor(private count: number,\n private source: Observable) {\n }\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RepeatSubscriber extends Subscriber {\n constructor(destination: Subscriber,\n private count: number,\n private source: Observable) {\n super(destination);\n }\n complete() {\n if (!this.isStopped) {\n const { source, count } = this;\n if (count === 0) {\n return super.complete();\n } else if (count > -1) {\n this.count = count - 1;\n }\n source.subscribe(this._unsubscribeAndRecycle());\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source\n * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable\n * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise\n * this method will resubscribe to the source Observable.\n *\n * ![](repeatWhen.png)\n *\n * ## Example\n * Repeat a message stream on click\n * ```ts\n * import { of, fromEvent } from 'rxjs';\n * import { repeatWhen } from 'rxjs/operators';\n *\n * const source = of('Repeat message');\n * const documentClick$ = fromEvent(document, 'click');\n *\n * source.pipe(repeatWhen(() => documentClick$)\n * ).subscribe(data => console.log(data))\n * ```\n * @see {@link repeat}\n * @see {@link retry}\n * @see {@link retryWhen}\n *\n * @param {function(notifications: Observable): Observable} notifier - Receives an Observable of notifications with\n * which a user can `complete` or `error`, aborting the repetition.\n * @return {Observable} The source Observable modified with repeat logic.\n * @method repeatWhen\n * @owner Observable\n */\nexport function repeatWhen(notifier: (notifications: Observable) => Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new RepeatWhenOperator(notifier));\n}\n\nclass RepeatWhenOperator implements Operator {\n constructor(protected notifier: (notifications: Observable) => Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RepeatWhenSubscriber extends OuterSubscriber {\n\n private notifications: Subject;\n private retries: Observable;\n private retriesSubscription: Subscription;\n private sourceIsBeingSubscribedTo: boolean = true;\n\n constructor(destination: Subscriber,\n private notifier: (notifications: Observable) => Observable,\n private source: Observable) {\n super(destination);\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.sourceIsBeingSubscribedTo = true;\n this.source.subscribe(this);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n if (this.sourceIsBeingSubscribedTo === false) {\n return super.complete();\n }\n }\n\n complete() {\n this.sourceIsBeingSubscribedTo = false;\n\n if (!this.isStopped) {\n if (!this.retries) {\n this.subscribeToRetries();\n }\n if (!this.retriesSubscription || this.retriesSubscription.closed) {\n return super.complete();\n }\n\n this._unsubscribeAndRecycle();\n this.notifications.next();\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { notifications, retriesSubscription } = this;\n if (notifications) {\n notifications.unsubscribe();\n this.notifications = null;\n }\n if (retriesSubscription) {\n retriesSubscription.unsubscribe();\n this.retriesSubscription = null;\n }\n this.retries = null;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribeAndRecycle(): Subscriber {\n const { _unsubscribe } = this;\n\n this._unsubscribe = null;\n super._unsubscribeAndRecycle();\n this._unsubscribe = _unsubscribe;\n\n return this;\n }\n\n private subscribeToRetries() {\n this.notifications = new Subject();\n let retries;\n try {\n const { notifier } = this;\n retries = notifier(this.notifications);\n } catch (e) {\n return super.complete();\n }\n this.retries = retries;\n this.retriesSubscription = subscribeToResult(this, retries);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given\n * as a number parameter) rather than propagating the `error` call.\n *\n * ![](retry.png)\n *\n * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted\n * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second\n * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications\n * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].\n *\n * ## Example\n * ```ts\n * import { interval, of, throwError } from 'rxjs';\n * import { mergeMap, retry } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const example = source.pipe(\n * mergeMap(val => {\n * if(val > 5){\n * return throwError('Error!');\n * }\n * return of(val);\n * }),\n * //retry 2 times on error\n * retry(2)\n * );\n *\n * const subscribe = example.subscribe({\n * next: val => console.log(val),\n * error: val => console.log(`${val}: Retried 2 times then quit!`)\n * });\n *\n * // Output:\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // \"Error!: Retried 2 times then quit!\"\n * ```\n *\n * @param {number} count - Number of retry attempts before failing.\n * @return {Observable} The source Observable modified with the retry logic.\n * @method retry\n * @owner Observable\n */\nexport function retry(count: number = -1): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new RetryOperator(count, source));\n}\n\nclass RetryOperator implements Operator {\n constructor(private count: number,\n private source: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RetrySubscriber extends Subscriber {\n constructor(destination: Subscriber,\n private count: number,\n private source: Observable) {\n super(destination);\n }\n error(err: any) {\n if (!this.isStopped) {\n const { source, count } = this;\n if (count === 0) {\n return super.error(err);\n } else if (count > -1) {\n this.count = count - 1;\n }\n source.subscribe(this._unsubscribeAndRecycle());\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.\n * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child\n * subscription. Otherwise this method will resubscribe to the source Observable.\n *\n * ![](retryWhen.png)\n *\n * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a\n * user can `complete` or `error`, aborting the retry.\n * @return {Observable} The source Observable modified with retry logic.\n * @method retryWhen\n * @owner Observable\n */\nexport function retryWhen(notifier: (errors: Observable) => Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new RetryWhenOperator(notifier, source));\n}\n\nclass RetryWhenOperator implements Operator {\n constructor(protected notifier: (errors: Observable) => Observable,\n protected source: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass RetryWhenSubscriber extends OuterSubscriber {\n\n private errors: Subject;\n private retries: Observable;\n private retriesSubscription: Subscription;\n\n constructor(destination: Subscriber,\n private notifier: (errors: Observable) => Observable,\n private source: Observable) {\n super(destination);\n }\n\n error(err: any) {\n if (!this.isStopped) {\n\n let errors = this.errors;\n let retries: any = this.retries;\n let retriesSubscription = this.retriesSubscription;\n\n if (!retries) {\n errors = new Subject();\n try {\n const { notifier } = this;\n retries = notifier(errors);\n } catch (e) {\n return super.error(e);\n }\n retriesSubscription = subscribeToResult(this, retries);\n } else {\n this.errors = null;\n this.retriesSubscription = null;\n }\n\n this._unsubscribeAndRecycle();\n\n this.errors = errors;\n this.retries = retries;\n this.retriesSubscription = retriesSubscription;\n\n errors.next(err);\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { errors, retriesSubscription } = this;\n if (errors) {\n errors.unsubscribe();\n this.errors = null;\n }\n if (retriesSubscription) {\n retriesSubscription.unsubscribe();\n this.retriesSubscription = null;\n }\n this.retries = null;\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n const { _unsubscribe } = this;\n\n this._unsubscribe = null;\n this._unsubscribeAndRecycle();\n this._unsubscribe = _unsubscribe;\n\n this.source.subscribe(this);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits the most recently emitted value from the source Observable whenever\n * another Observable, the `notifier`, emits.\n *\n * It's like {@link sampleTime}, but samples whenever\n * the `notifier` Observable emits something.\n *\n * ![](sample.png)\n *\n * Whenever the `notifier` Observable emits a value or completes, `sample`\n * looks at the source Observable and emits whichever value it has most recently\n * emitted since the previous sampling, unless the source has not emitted\n * anything since the previous sampling. The `notifier` is subscribed to as soon\n * as the output Observable is subscribed.\n *\n * ## Example\n * On every click, sample the most recent \"seconds\" timer\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { sample } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = seconds.pipe(sample(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param {Observable} notifier The Observable to use for sampling the\n * source Observable.\n * @return {Observable} An Observable that emits the results of sampling the\n * values emitted by the source Observable whenever the notifier Observable\n * emits value or completes.\n * @method sample\n * @owner Observable\n */\nexport function sample(notifier: Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SampleOperator(notifier));\n}\n\nclass SampleOperator implements Operator {\n constructor(private notifier: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n const sampleSubscriber = new SampleSubscriber(subscriber);\n const subscription = source.subscribe(sampleSubscriber);\n subscription.add(subscribeToResult(sampleSubscriber, this.notifier));\n return subscription;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SampleSubscriber extends OuterSubscriber {\n private value: T;\n private hasValue: boolean = false;\n\n protected _next(value: T) {\n this.value = value;\n this.hasValue = true;\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.emitValue();\n }\n\n notifyComplete(): void {\n this.emitValue();\n }\n\n emitValue() {\n if (this.hasValue) {\n this.hasValue = false;\n this.destination.next(this.value);\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits the most recently emitted value from the source Observable within\n * periodic time intervals.\n *\n * Samples the source Observable at periodic time\n * intervals, emitting what it samples.\n *\n * ![](sampleTime.png)\n *\n * `sampleTime` periodically looks at the source Observable and emits whichever\n * value it has most recently emitted since the previous sampling, unless the\n * source has not emitted anything since the previous sampling. The sampling\n * happens periodically in time every `period` milliseconds (or the time unit\n * defined by the optional `scheduler` argument). The sampling starts as soon as\n * the output Observable is subscribed.\n *\n * ## Example\n * Every second, emit the most recent click at most once\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { sampleTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(sampleTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param {number} period The sampling period expressed in milliseconds or the\n * time unit determined internally by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the sampling.\n * @return {Observable} An Observable that emits the results of sampling the\n * values emitted by the source Observable at the specified time interval.\n * @method sampleTime\n * @owner Observable\n */\nexport function sampleTime(period: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SampleTimeOperator(period, scheduler));\n}\n\nclass SampleTimeOperator implements Operator {\n constructor(private period: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SampleTimeSubscriber extends Subscriber {\n lastValue: T;\n hasValue: boolean = false;\n\n constructor(destination: Subscriber,\n private period: number,\n private scheduler: SchedulerLike) {\n super(destination);\n this.add(scheduler.schedule(dispatchNotification, period, { subscriber: this, period }));\n }\n\n protected _next(value: T) {\n this.lastValue = value;\n this.hasValue = true;\n }\n\n notifyNext() {\n if (this.hasValue) {\n this.hasValue = false;\n this.destination.next(this.lastValue);\n }\n }\n}\n\nfunction dispatchNotification(this: SchedulerAction, state: any) {\n let { subscriber, period } = state;\n subscriber.notifyNext();\n this.schedule(state, period);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\nimport { Observer, OperatorFunction } from '../types';\n\n/**\n * Compares all values of two observables in sequence using an optional comparator function\n * and returns an observable of a single boolean value representing whether or not the two sequences\n * are equal.\n *\n * Checks to see of all values emitted by both observables are equal, in order.\n *\n * ![](sequenceEqual.png)\n *\n * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either\n * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom\n * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the\n * observables completes, the operator will wait for the other observable to complete; If the other\n * observable emits before completing, the returned observable will emit `false` and complete. If one observable never\n * completes or emits after the other complets, the returned observable will never complete.\n *\n * ## Example\n * figure out if the Konami code matches\n * ```ts\n * import { from, fromEvent } from 'rxjs';\n * import { sequenceEqual, bufferCount, mergeMap, map } from 'rxjs/operators';\n *\n * const codes = from([\n * 'ArrowUp',\n * 'ArrowUp',\n * 'ArrowDown',\n * 'ArrowDown',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'KeyB',\n * 'KeyA',\n * 'Enter', // no start key, clearly.\n * ]);\n *\n * const keys = fromEvent(document, 'keyup').pipe(map(e => e.code));\n * const matches = keys.pipe(\n * bufferCount(11, 1),\n * mergeMap(\n * last11 => from(last11).pipe(sequenceEqual(codes)),\n * ),\n * );\n * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n * @see {@link withLatestFrom}\n *\n * @param {Observable} compareTo The observable sequence to compare the source sequence to.\n * @param {function} [comparator] An optional function to compare each value pair\n * @return {Observable} An Observable of a single boolean value representing whether or not\n * the values emitted by both observables were equal in sequence.\n * @method sequenceEqual\n * @owner Observable\n */\nexport function sequenceEqual(compareTo: Observable,\n comparator?: (a: T, b: T) => boolean): OperatorFunction {\n return (source: Observable) => source.lift(new SequenceEqualOperator(compareTo, comparator));\n}\n\nexport class SequenceEqualOperator implements Operator {\n constructor(private compareTo: Observable,\n private comparator: (a: T, b: T) => boolean) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SequenceEqualSubscriber extends Subscriber {\n private _a: T[] = [];\n private _b: T[] = [];\n private _oneComplete = false;\n\n constructor(destination: Observer,\n private compareTo: Observable,\n private comparator: (a: T, b: T) => boolean) {\n super(destination);\n (this.destination as Subscription).add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));\n }\n\n protected _next(value: T): void {\n if (this._oneComplete && this._b.length === 0) {\n this.emit(false);\n } else {\n this._a.push(value);\n this.checkValues();\n }\n }\n\n public _complete(): void {\n if (this._oneComplete) {\n this.emit(this._a.length === 0 && this._b.length === 0);\n } else {\n this._oneComplete = true;\n }\n this.unsubscribe();\n }\n\n checkValues() {\n const { _a, _b, comparator } = this;\n while (_a.length > 0 && _b.length > 0) {\n let a = _a.shift();\n let b = _b.shift();\n let areEqual = false;\n try {\n areEqual = comparator ? comparator(a, b) : a === b;\n } catch (e) {\n this.destination.error(e);\n }\n if (!areEqual) {\n this.emit(false);\n }\n }\n }\n\n emit(value: boolean) {\n const { destination } = this;\n destination.next(value);\n destination.complete();\n }\n\n nextB(value: T) {\n if (this._oneComplete && this._a.length === 0) {\n this.emit(false);\n } else {\n this._b.push(value);\n this.checkValues();\n }\n }\n\n completeB() {\n if (this._oneComplete) {\n this.emit(this._a.length === 0 && this._b.length === 0);\n } else {\n this._oneComplete = true;\n }\n }\n}\n\nclass SequenceEqualCompareToSubscriber extends Subscriber {\n constructor(destination: Observer, private parent: SequenceEqualSubscriber) {\n super(destination);\n }\n\n protected _next(value: T): void {\n this.parent.nextB(value);\n }\n\n protected _error(err: any): void {\n this.parent.error(err);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.completeB();\n this.unsubscribe();\n }\n}\n","import { Observable } from '../Observable';\nimport { multicast } from './multicast';\nimport { refCount } from './refCount';\nimport { Subject } from '../Subject';\n\nimport { MonoTypeOperatorFunction } from '../types';\n\nfunction shareSubjectFactory() {\n return new Subject();\n}\n\n/**\n * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one\n * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will\n * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.\n * This is an alias for `multicast(() => new Subject()), refCount()`.\n *\n * ![](share.png)\n *\n * @return {Observable} An Observable that upon connection causes the source Observable to emit items to its Observers.\n * @method share\n * @owner Observable\n */\nexport function share(): MonoTypeOperatorFunction {\n return (source: Observable) => refCount()(multicast(shareSubjectFactory)(source)) as Observable;\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\nexport interface ShareReplayConfig {\n bufferSize?: number;\n windowTime?: number;\n refCount: boolean;\n scheduler?: SchedulerLike;\n}\n\n/**\n * Share source and replay specified number of emissions on subscription.\n *\n * This operator is a specialization of `replay` that connects to a source observable\n * and multicasts through a `ReplaySubject` constructed with the specified arguments.\n * A successfully completed source will stay cached in the `shareReplayed observable` forever,\n * but an errored source can be retried.\n *\n * ## Why use shareReplay?\n * You generally want to use `shareReplay` when you have side-effects or taxing computations\n * that you do not wish to be executed amongst multiple subscribers.\n * It may also be valuable in situations where you know you will have late subscribers to\n * a stream that need access to previously emitted values.\n * This ability to replay values on subscription is what differentiates {@link share} and `shareReplay`.\n *\n * ![](shareReplay.png)\n *\n * ## Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { shareReplay, take } from 'rxjs/operators';\n *\n * const obs$ = interval(1000);\n * const shared$ = obs$.pipe(\n * take(4),\n * shareReplay(3)\n * );\n * shared$.subscribe(x => console.log('source A: ', x));\n * shared$.subscribe(y => console.log('source B: ', y));\n *\n * ```\n *\n * @see {@link publish}\n * @see {@link share}\n * @see {@link publishReplay}\n *\n * @param {Number} [bufferSize=Number.POSITIVE_INFINITY] Maximum element count of the replay buffer.\n * @param {Number} [windowTime=Number.POSITIVE_INFINITY] Maximum time length of the replay buffer in milliseconds.\n * @param {Scheduler} [scheduler] Scheduler where connected observers within the selector function\n * will be invoked on.\n * @return {Observable} An observable sequence that contains the elements of a sequence produced\n * by multicasting the source sequence within a selector function.\n * @method shareReplay\n * @owner Observable\n */\nexport function shareReplay(config: ShareReplayConfig): MonoTypeOperatorFunction;\nexport function shareReplay(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction;\nexport function shareReplay(\n configOrBufferSize?: ShareReplayConfig | number,\n windowTime?: number,\n scheduler?: SchedulerLike\n): MonoTypeOperatorFunction {\n let config: ShareReplayConfig;\n if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n config = configOrBufferSize as ShareReplayConfig;\n } else {\n config = {\n bufferSize: configOrBufferSize as number | undefined,\n windowTime,\n refCount: false,\n scheduler\n };\n }\n return (source: Observable) => source.lift(shareReplayOperator(config));\n}\n\nfunction shareReplayOperator({\n bufferSize = Number.POSITIVE_INFINITY,\n windowTime = Number.POSITIVE_INFINITY,\n refCount: useRefCount,\n scheduler\n}: ShareReplayConfig) {\n let subject: ReplaySubject | undefined;\n let refCount = 0;\n let subscription: Subscription | undefined;\n let hasError = false;\n let isComplete = false;\n\n return function shareReplayOperation(this: Subscriber, source: Observable) {\n refCount++;\n if (!subject || hasError) {\n hasError = false;\n subject = new ReplaySubject(bufferSize, windowTime, scheduler);\n subscription = source.subscribe({\n next(value) { subject.next(value); },\n error(err) {\n hasError = true;\n subject.error(err);\n },\n complete() {\n isComplete = true;\n subject.complete();\n },\n });\n }\n\n const innerSub = subject.subscribe(this);\n this.add(() => {\n refCount--;\n innerSub.unsubscribe();\n if (subscription && !isComplete && useRefCount && refCount === 0) {\n subscription.unsubscribe();\n subscription = undefined;\n subject = undefined;\n }\n });\n };\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { EmptyError } from '../util/EmptyError';\n\nimport { Observer, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that emits the single item emitted by the source Observable that matches a specified\n * predicate, if that Observable emits one such item. If the source Observable emits more than one such item or no\n * items, notify of an IllegalArgumentException or NoSuchElementException respectively. If the source Observable\n * emits items but none match the specified predicate then `undefined` is emitted.\n *\n * Like {@link first}, but emit with error notification if there is more than one value.\n * ![](single.png)\n *\n * ## Example\n * emits 'error'\n * ```ts\n * import { range } from 'rxjs';\n * import { single } from 'rxjs/operators';\n *\n * const numbers = range(1,5).pipe(single());\n * numbers.subscribe(x => console.log('never get called'), e => console.log('error'));\n * // result\n * // 'error'\n * ```\n *\n * emits 'undefined'\n * ```ts\n * import { range } from 'rxjs';\n * import { single } from 'rxjs/operators';\n *\n * const numbers = range(1,5).pipe(single(x => x === 10));\n * numbers.subscribe(x => console.log(x));\n * // result\n * // 'undefined'\n * ```\n *\n * @see {@link first}\n * @see {@link find}\n * @see {@link findIndex}\n * @see {@link elementAt}\n *\n * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @param {Function} predicate - A predicate function to evaluate items emitted by the source Observable.\n * @return {Observable} An Observable that emits the single item emitted by the source Observable that matches\n * the predicate or `undefined` when no items match.\n *\n * @method single\n * @owner Observable\n */\nexport function single(predicate?: (value: T, index: number, source: Observable) => boolean): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SingleOperator(predicate, source));\n}\n\nclass SingleOperator implements Operator {\n constructor(private predicate?: (value: T, index: number, source: Observable) => boolean,\n private source?: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SingleSubscriber extends Subscriber {\n private seenValue: boolean = false;\n private singleValue: T;\n private index: number = 0;\n\n constructor(destination: Observer,\n private predicate?: (value: T, index: number, source: Observable) => boolean,\n private source?: Observable) {\n super(destination);\n }\n\n private applySingleValue(value: T): void {\n if (this.seenValue) {\n this.destination.error('Sequence contains more than one element');\n } else {\n this.seenValue = true;\n this.singleValue = value;\n }\n }\n\n protected _next(value: T): void {\n const index = this.index++;\n\n if (this.predicate) {\n this.tryNext(value, index);\n } else {\n this.applySingleValue(value);\n }\n }\n\n private tryNext(value: T, index: number): void {\n try {\n if (this.predicate(value, index, this.source)) {\n this.applySingleValue(value);\n }\n } catch (err) {\n this.destination.error(err);\n }\n }\n\n protected _complete(): void {\n const destination = this.destination;\n\n if (this.index > 0) {\n destination.next(this.seenValue ? this.singleValue : undefined);\n destination.complete();\n } else {\n destination.error(new EmptyError);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * ![](skip.png)\n *\n * @param {Number} count - The number of times, items emitted by source Observable should be skipped.\n * @return {Observable} An Observable that skips values emitted by the source Observable.\n *\n * @method skip\n * @owner Observable\n */\nexport function skip(count: number): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SkipOperator(count));\n}\n\nclass SkipOperator implements Operator {\n constructor(private total: number) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SkipSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipSubscriber extends Subscriber {\n count: number = 0;\n\n constructor(destination: Subscriber, private total: number) {\n super(destination);\n }\n\n protected _next(x: T) {\n if (++this.count > this.total) {\n this.destination.next(x);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Skip the last `count` values emitted by the source Observable.\n *\n * ![](skipLast.png)\n *\n * `skipLast` returns an Observable that accumulates a queue with a length\n * enough to store the first `count` values. As more values are received,\n * values are taken from the front of the queue and produced on the result\n * sequence. This causes values to be delayed.\n *\n * ## Example\n * Skip the last 2 values of an Observable with many values\n * ```ts\n * import { range } from 'rxjs';\n * import { skipLast } from 'rxjs/operators';\n *\n * const many = range(1, 5);\n * const skipLastTwo = many.pipe(skipLast(2));\n * skipLastTwo.subscribe(x => console.log(x));\n *\n * // Results in:\n * // 1 2 3\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipWhile}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws\n * ArgumentOutOrRangeError if `i < 0`.\n *\n * @param {number} count Number of elements to skip from the end of the source Observable.\n * @returns {Observable} An Observable that skips the last count values\n * emitted by the source Observable.\n * @method skipLast\n * @owner Observable\n */\nexport function skipLast(count: number): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SkipLastOperator(count));\n}\n\nclass SkipLastOperator implements Operator {\n constructor(private _skipCount: number) {\n if (this._skipCount < 0) {\n throw new ArgumentOutOfRangeError;\n }\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n if (this._skipCount === 0) {\n // If we don't want to skip any values then just subscribe\n // to Subscriber without any further logic.\n return source.subscribe(new Subscriber(subscriber));\n } else {\n return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipLastSubscriber extends Subscriber {\n private _ring: T[];\n private _count: number = 0;\n\n constructor(destination: Subscriber, private _skipCount: number) {\n super(destination);\n this._ring = new Array(_skipCount);\n }\n\n protected _next(value: T): void {\n const skipCount = this._skipCount;\n const count = this._count++;\n\n if (count < skipCount) {\n this._ring[count] = value;\n } else {\n const currentIndex = count % skipCount;\n const ring = this._ring;\n const oldValue = ring[currentIndex];\n\n ring[currentIndex] = value;\n this.destination.next(oldValue);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { MonoTypeOperatorFunction, TeardownLogic, ObservableInput } from '../types';\nimport { Subscription } from '../Subscription';\n\n/**\n * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.\n *\n * The `skipUntil` operator causes the observable stream to skip the emission of values ​​until the passed in observable emits the first value.\n * This can be particularly useful in combination with user interactions, responses of http requests or waiting for specific times to pass by.\n *\n * ![](skipUntil.png)\n *\n * Internally the `skipUntil` operator subscribes to the passed in observable (in the following called *notifier*) in order to recognize the emission\n * of its first value. When this happens, the operator unsubscribes from the *notifier* and starts emitting the values of the *source*\n * observable. It will never let the *source* observable emit any values if the *notifier* completes or throws an error without emitting\n * a value before.\n *\n * ## Example\n *\n * In the following example, all emitted values ​​of the interval observable are skipped until the user clicks anywhere within the page.\n *\n * ```ts\n * import { interval, fromEvent } from 'rxjs';\n * import { skipUntil } from 'rxjs/operators';\n *\n * const intervalObservable = interval(1000);\n * const click = fromEvent(document, 'click');\n *\n * const emitAfterClick = intervalObservable.pipe(\n * skipUntil(click)\n * );\n * // clicked at 4.6s. output: 5...6...7...8........ or\n * // clicked at 7.3s. output: 8...9...10..11.......\n * const subscribe = emitAfterClick.subscribe(value => console.log(value));\n * ```\n *\n * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to\n * be mirrored by the resulting Observable.\n * @return {Observable} An Observable that skips items from the source Observable until the second Observable emits\n * an item, then emits the remaining items.\n * @method skipUntil\n * @owner Observable\n */\nexport function skipUntil(notifier: Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SkipUntilOperator(notifier));\n}\n\nclass SkipUntilOperator implements Operator {\n constructor(private notifier: Observable) {\n }\n\n call(destination: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipUntilSubscriber extends OuterSubscriber {\n\n private hasValue: boolean = false;\n private innerSubscription: Subscription;\n\n constructor(destination: Subscriber, notifier: ObservableInput) {\n super(destination);\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n this.add(innerSubscriber);\n this.innerSubscription = innerSubscriber;\n subscribeToResult(this, notifier, undefined, undefined, innerSubscriber);\n }\n\n protected _next(value: T) {\n if (this.hasValue) {\n super._next(value);\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.hasValue = true;\n if (this.innerSubscription) {\n this.innerSubscription.unsubscribe();\n }\n }\n\n notifyComplete() {\n /* do nothing */\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds\n * true, but emits all further source items as soon as the condition becomes false.\n *\n * ![](skipWhile.png)\n *\n * @param {Function} predicate - A function to test each item emitted from the source Observable.\n * @return {Observable} An Observable that begins emitting items emitted by the source Observable when the\n * specified predicate becomes false.\n * @method skipWhile\n * @owner Observable\n */\nexport function skipWhile(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new SkipWhileOperator(predicate));\n}\n\nclass SkipWhileOperator implements Operator {\n constructor(private predicate: (value: T, index: number) => boolean) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipWhileSubscriber extends Subscriber {\n private skipping: boolean = true;\n private index: number = 0;\n\n constructor(destination: Subscriber,\n private predicate: (value: T, index: number) => boolean) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const destination = this.destination;\n if (this.skipping) {\n this.tryCallPredicate(value);\n }\n\n if (!this.skipping) {\n destination.next(value);\n }\n }\n\n private tryCallPredicate(value: T): void {\n try {\n const result = this.predicate(value, this.index++);\n this.skipping = Boolean(result);\n } catch (err) {\n this.destination.error(err);\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nimport { MonoTypeOperatorFunction, OperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(scheduler: SchedulerLike): MonoTypeOperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, v2: E, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, v2: E, v3: F, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, v2: E, v3: F, v4: G, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, v2: E, v3: F, v4: G, v5: H, scheduler: SchedulerLike): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I, scheduler: SchedulerLike): OperatorFunction;\n\nexport function startWith(v1: D): OperatorFunction;\nexport function startWith(v1: D, v2: E): OperatorFunction;\nexport function startWith(v1: D, v2: E, v3: F): OperatorFunction;\nexport function startWith(v1: D, v2: E, v3: F, v4: G): OperatorFunction;\nexport function startWith(v1: D, v2: E, v3: F, v4: G, v5: H): OperatorFunction;\nexport function startWith(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I): OperatorFunction;\nexport function startWith(...array: D[]): OperatorFunction;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith(...array: Array): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments before it begins to emit\n * items emitted by the source Observable.\n *\n * First emits its arguments in order, and then any\n * emissions from the source.\n *\n * ![](startWith.png)\n *\n * ## Examples\n *\n * Start the chain of emissions with `\"first\"`, `\"second\"`\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * of(\"from source\")\n * .pipe(startWith(\"first\", \"second\"))\n * .subscribe(x => console.log(x));\n *\n * // results:\n * // \"first\"\n * // \"second\"\n * // \"from source\"\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit first.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items\n * emitted by the source Observable.\n * @method startWith\n * @owner Observable\n */\nexport function startWith(...array: Array): OperatorFunction {\n const scheduler = array[array.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n // deprecated path\n array.pop();\n return (source: Observable) => concat(array as T[], source, scheduler);\n } else {\n return (source: Observable) => concat(array as T[], source);\n }\n}\n","import { SchedulerLike, SchedulerAction } from '../types';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { asap } from '../scheduler/asap';\nimport { isNumeric } from '../util/isNumeric';\n\nexport interface DispatchArg {\n source: Observable;\n subscriber: Subscriber;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @extends {Ignored}\n * @hide true\n */\nexport class SubscribeOnObservable extends Observable {\n /** @nocollapse */\n static create(source: Observable, delay: number = 0, scheduler: SchedulerLike = asap): Observable {\n return new SubscribeOnObservable(source, delay, scheduler);\n }\n\n /** @nocollapse */\n static dispatch(this: SchedulerAction, arg: DispatchArg): Subscription {\n const { source, subscriber } = arg;\n return this.add(source.subscribe(subscriber));\n }\n\n constructor(public source: Observable,\n private delayTime: number = 0,\n private scheduler: SchedulerLike = asap) {\n super();\n if (!isNumeric(delayTime) || delayTime < 0) {\n this.delayTime = 0;\n }\n if (!scheduler || typeof scheduler.schedule !== 'function') {\n this.scheduler = asap;\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber) {\n const delay = this.delayTime;\n const source = this.source;\n const scheduler = this.scheduler;\n\n return scheduler.schedule>(SubscribeOnObservable.dispatch, delay, {\n source, subscriber\n });\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { SubscribeOnObservable } from '../observable/SubscribeOnObservable';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}.\n *\n * With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to.\n *\n * Schedulers control the speed and order of emissions to observers from an Observable stream.\n *\n * ![](subscribeOn.png)\n *\n * ## Example\n * Given the following code:\n * ```javascript\n * import { of, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3, 4);\n * const b = of(5, 6, 7, 8, 9);\n * merge(a, b).subscribe(console.log);\n * ```\n *\n * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to.\n * This will result in the output of `1 2 3 4 5 6 7 8 9`.\n *\n * But if we instead us the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emited by Observable `a`:\n * ```javascript\n * import { of, merge, asyncScheduler } from 'rxjs';\n * import { subscribeOn } from 'rxjs/operators';\n *\n * const a = of(1, 2, 3, 4).pipe(subscribeOn(asyncScheduler));\n * const b = of(5, 6, 7, 8, 9);\n * merge(a, b).subscribe(console.log);\n * ```\n *\n * The output will instead be `5 6 7 8 9 1 2 3 4`.\n * The reason for this is that Observable `b` emits its values directly and synchronously like before\n * but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable.\n *\n * @param {SchedulerLike} scheduler - The {@link SchedulerLike} to perform subscription actions on.\n * @return {Observable} The source Observable modified so that its subscriptions happen on the specified {@link SchedulerLike}.\n .\n * @method subscribeOn\n * @owner Observable\n */\nexport function subscribeOn(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction {\n return function subscribeOnOperatorFunction(source: Observable): Observable {\n return source.lift(new SubscribeOnOperator(scheduler, delay));\n };\n}\n\nclass SubscribeOnOperator implements Operator {\n constructor(private scheduler: SchedulerLike,\n private delay: number) {\n }\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return new SubscribeOnObservable(\n source, this.delay, this.scheduler\n ).subscribe(subscriber);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\n\n/* tslint:disable:max-line-length */\nexport function switchMap>(project: (value: T, index: number) => O): OperatorFunction>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * Maps each value to an Observable, then flattens all of\n * these inner Observables.\n *\n * ![](switchMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n * Generate new Observable according to source Observable values\n * ```typescript\n * import { of } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // ... and so on\n * ```\n *\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap((ev) => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and taking only the values from the most recently\n * projected inner Observable.\n * @method switchMap\n * @owner Observable\n */\nexport function switchMap>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction|R> {\n if (typeof resultSelector === 'function') {\n return (source: Observable) => source.pipe(\n switchMap((a, i) => from(project(a, i)).pipe(\n map((b, ii) => resultSelector(a, b, i, ii))\n ))\n );\n }\n return (source: Observable) => source.lift(new SwitchMapOperator(project));\n}\n\nclass SwitchMapOperator implements Operator {\n constructor(private project: (value: T, index: number) => ObservableInput) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchMapSubscriber extends OuterSubscriber {\n private index: number = 0;\n private innerSubscription: Subscription;\n\n constructor(destination: Subscriber,\n private project: (value: T, index: number) => ObservableInput) {\n super(destination);\n }\n\n protected _next(value: T) {\n let result: ObservableInput;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (error) {\n this.destination.error(error);\n return;\n }\n this._innerSub(result, value, index);\n }\n\n private _innerSub(result: ObservableInput, value: T, index: number) {\n const innerSubscription = this.innerSubscription;\n if (innerSubscription) {\n innerSubscription.unsubscribe();\n }\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n this.innerSubscription = subscribeToResult(this, result, value, index, innerSubscriber);\n }\n\n protected _complete(): void {\n const {innerSubscription} = this;\n if (!innerSubscription || innerSubscription.closed) {\n super._complete();\n }\n this.unsubscribe();\n }\n\n protected _unsubscribe() {\n this.innerSubscription = null;\n }\n\n notifyComplete(innerSub: Subscription): void {\n const destination = this.destination as Subscription;\n destination.remove(innerSub);\n this.innerSubscription = null;\n if (this.isStopped) {\n super._complete();\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.destination.next(innerValue);\n }\n}\n","import {OperatorFunction, ObservableInput} from '../types';\nimport { switchMap } from './switchMap';\nimport { identity } from '../util/identity';\n\nexport function switchAll(): OperatorFunction, T>;\nexport function switchAll(): OperatorFunction;\n\n/**\n * Converts a higher-order Observable into a first-order Observable\n * producing values only from the most recent observable sequence\n *\n * Flattens an Observable-of-Observables.\n *\n * ![](switchAll.png)\n *\n * `switchAll` subscribes to a source that is an observable of observables, also known as a\n * \"higher-order observable\" (or `Observable>`). It subscribes to the most recently\n * provided \"inner observable\" emitted by the source, unsubscribing from any previously subscribed\n * to inner observable, such that only the most recent inner observable may be subscribed to at\n * any point in time. The resulting observable returned by `switchAll` will only complete if the\n * source observable completes, *and* any currently subscribed to inner observable also has completed,\n * if there are any.\n *\n * ## Examples\n * Spawn a new interval observable for each click event, but for every new\n * click, cancel the previous interval and subscribe to the new one.\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchAll, map, tap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click')));\n * const source = clicks.pipe(map((ev) => interval(1000)));\n *\n * source.pipe(\n * switchAll()\n * ).subscribe(x => console.log(x));\n *\n /* Output\n * click\n * 1\n * 2\n * 3\n * 4\n * ...\n * click\n * 1\n * 2\n * 3\n * ...\n * click\n * ...\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link switchMap}\n * @see {@link switchMapTo}\n * @see {@link mergeAll}\n */\n\nexport function switchAll(): OperatorFunction, T> {\n return switchMap(identity);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { switchMap } from './switchMap';\n\n/* tslint:disable:max-line-length */\nexport function switchMapTo(observable: ObservableInput): OperatorFunction;\n/** @deprecated resultSelector is no longer supported. Switch to using switchMap with an inner map */\nexport function switchMapTo(observable: ObservableInput, resultSelector: undefined): OperatorFunction;\n/** @deprecated resultSelector is no longer supported. Switch to using switchMap with an inner map */\nexport function switchMapTo(observable: ObservableInput, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is flattened multiple\n * times with {@link switchMap} in the output Observable.\n *\n * It's like {@link switchMap}, but maps each value\n * always to the same inner Observable.\n *\n * ![](switchMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. The output Observables\n * emits values only from the most recently emitted instance of\n * `innerObservable`.\n *\n * ## Example\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMapTo } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeMapTo}\n *\n * @param {ObservableInput} innerObservable An Observable to replace each value from\n * the source Observable.\n * @return {Observable} An Observable that emits items from the given\n * `innerObservable` (and optionally transformed through the deprecated `resultSelector`)\n * every time a value is emitted on the source Observable, and taking only the values\n * from the most recently projected inner Observable.\n * @method switchMapTo\n * @owner Observable\n */\nexport function switchMapTo(\n innerObservable: ObservableInput,\n resultSelector?: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R\n): OperatorFunction {\n return resultSelector ? switchMap(() => innerObservable, resultSelector) : switchMap(() => innerObservable);\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits the values emitted by the source Observable until a `notifier`\n * Observable emits a value.\n *\n * Lets values pass until a second Observable,\n * `notifier`, emits a value. Then, it completes.\n *\n * ![](takeUntil.png)\n *\n * `takeUntil` subscribes and begins mirroring the source Observable. It also\n * monitors a second Observable, `notifier` that you provide. If the `notifier`\n * emits a value, the output Observable stops mirroring the source Observable\n * and completes. If the `notifier` doesn't emit any value and completes\n * then `takeUntil` will pass all values.\n *\n * ## Example\n * Tick every second until the first click happens\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { takeUntil } from 'rxjs/operators';\n *\n * const source = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = source.pipe(takeUntil(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param {Observable} notifier The Observable whose first emitted value will\n * cause the output Observable of `takeUntil` to stop emitting values from the\n * source Observable.\n * @return {Observable} An Observable that emits the values from the source\n * Observable until such time as `notifier` emits its first value.\n * @method takeUntil\n * @owner Observable\n */\nexport function takeUntil(notifier: Observable): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new TakeUntilOperator(notifier));\n}\n\nclass TakeUntilOperator implements Operator {\n constructor(private notifier: Observable) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n const takeUntilSubscriber = new TakeUntilSubscriber(subscriber);\n const notifierSubscription = subscribeToResult(takeUntilSubscriber, this.notifier);\n if (notifierSubscription && !takeUntilSubscriber.seenValue) {\n takeUntilSubscriber.add(notifierSubscription);\n return source.subscribe(takeUntilSubscriber);\n }\n return takeUntilSubscriber;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeUntilSubscriber extends OuterSubscriber {\n seenValue = false;\n\n constructor(destination: Subscriber, ) {\n super(destination);\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.seenValue = true;\n this.complete();\n }\n\n notifyComplete(): void {\n // noop\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\nexport function takeWhile(predicate: (value: T, index: number) => value is S): OperatorFunction;\nexport function takeWhile(predicate: (value: T, index: number) => value is S, inclusive: false): OperatorFunction;\nexport function takeWhile(predicate: (value: T, index: number) => boolean, inclusive?: boolean): MonoTypeOperatorFunction;\n\n/**\n * Emits values emitted by the source Observable so long as each value satisfies\n * the given `predicate`, and then completes as soon as this `predicate` is not\n * satisfied.\n *\n * Takes values from the source only while they pass the\n * condition given. When the first value does not satisfy, it completes.\n *\n * ![](takeWhile.png)\n *\n * `takeWhile` subscribes and begins mirroring the source Observable. Each value\n * emitted on the source is given to the `predicate` function which returns a\n * boolean, representing a condition to be satisfied by the source values. The\n * output Observable emits the source values until such time as the `predicate`\n * returns false, at which point `takeWhile` stops mirroring the source\n * Observable and completes the output Observable.\n *\n * ## Example\n * Emit click events only while the clientX property is greater than 200\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { takeWhile } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(takeWhile(ev => ev.clientX > 200));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates a value emitted by the source Observable and returns a boolean.\n * Also takes the (zero-based) index as the second argument.\n * @param {boolean} inclusive When set to `true` the value that caused\n * `predicate` to return `false` will also be emitted.\n * @return {Observable} An Observable that emits the values from the source\n * Observable so long as each value satisfies the condition defined by the\n * `predicate`, then completes.\n * @method takeWhile\n * @owner Observable\n */\nexport function takeWhile(\n predicate: (value: T, index: number) => boolean,\n inclusive = false): MonoTypeOperatorFunction {\n return (source: Observable) =>\n source.lift(new TakeWhileOperator(predicate, inclusive));\n}\n\nclass TakeWhileOperator implements Operator {\n constructor(\n private predicate: (value: T, index: number) => boolean,\n private inclusive: boolean) {}\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(\n new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeWhileSubscriber extends Subscriber {\n private index: number = 0;\n\n constructor(\n destination: Subscriber,\n private predicate: (value: T, index: number) => boolean,\n private inclusive: boolean) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const destination = this.destination;\n let result: boolean;\n try {\n result = this.predicate(value, this.index++);\n } catch (err) {\n destination.error(err);\n return;\n }\n this.nextOrComplete(value, result);\n }\n\n private nextOrComplete(value: T, predicateResult: boolean): void {\n const destination = this.destination;\n if (Boolean(predicateResult)) {\n destination.next(value);\n } else {\n if (this.inclusive) {\n destination.next(value);\n }\n destination.complete();\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, TeardownLogic } from '../types';\nimport { noop } from '../util/noop';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap(next: null | undefined, error: null | undefined, complete: () => void): MonoTypeOperatorFunction;\n/** @deprecated Use an observer instead of an error callback */\nexport function tap(next: null | undefined, error: (error: any) => void, complete?: () => void): MonoTypeOperatorFunction;\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap(next: (value: T) => void, error: null | undefined, complete: () => void): MonoTypeOperatorFunction;\nexport function tap(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void): MonoTypeOperatorFunction;\nexport function tap(observer: PartialObserver): MonoTypeOperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * Perform a side effect for every emission on the source Observable, but return\n * an Observable that is identical to the source.\n *\n * Intercepts each emission on the source and runs a\n * function, but returns an output which is identical to the source as long as errors don't occur.\n *\n * ![](do.png)\n *\n * Returns a mirrored Observable of the source Observable, but modified so that\n * the provided Observer is called to perform a side effect for every value,\n * error, and completion emitted by the source. Any errors that are thrown in\n * the aforementioned Observer or handlers are safely sent down the error path\n * of the output Observable.\n *\n * This operator is useful for debugging your Observables for the correct values\n * or performing other side effects.\n *\n * Note: this is different to a `subscribe` on the Observable. If the Observable\n * returned by `tap` is not subscribed, the side effects specified by the\n * Observer will never happen. `tap` therefore simply spies on existing\n * execution, it does not trigger an execution to happen like `subscribe` does.\n *\n * ## Example\n * Map every click to the clientX position of that click, while also logging the click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { tap, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(\n * tap(ev => console.log(ev)),\n * map(ev => ev.clientX),\n * );\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n * @see {@link Observable#subscribe}\n *\n * @param {Observer|function} [nextOrObserver] A normal Observer object or a\n * callback for `next`.\n * @param {function} [error] Callback for errors in the source.\n * @param {function} [complete] Callback for the completion of the source.\n * @return {Observable} An Observable identical to the source, but runs the\n * specified Observer or callback(s) for each item.\n * @name tap\n */\nexport function tap(nextOrObserver?: PartialObserver | ((x: T) => void),\n error?: (e: any) => void,\n complete?: () => void): MonoTypeOperatorFunction {\n return function tapOperatorFunction(source: Observable): Observable {\n return source.lift(new DoOperator(nextOrObserver, error, complete));\n };\n}\n\nclass DoOperator implements Operator {\n constructor(private nextOrObserver?: PartialObserver | ((x: T) => void),\n private error?: (e: any) => void,\n private complete?: () => void) {\n }\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\n\nclass TapSubscriber extends Subscriber {\n private _context: any;\n\n private _tapNext: ((value: T) => void) = noop;\n\n private _tapError: ((err: any) => void) = noop;\n\n private _tapComplete: (() => void) = noop;\n\n constructor(destination: Subscriber,\n observerOrNext?: PartialObserver | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super(destination);\n this._tapError = error || noop;\n this._tapComplete = complete || noop;\n if (isFunction(observerOrNext)) {\n this._context = this;\n this._tapNext = observerOrNext;\n } else if (observerOrNext) {\n this._context = observerOrNext;\n this._tapNext = observerOrNext.next || noop;\n this._tapError = observerOrNext.error || noop;\n this._tapComplete = observerOrNext.complete || noop;\n }\n }\n\n _next(value: T) {\n try {\n this._tapNext.call(this._context, value);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(value);\n }\n\n _error(err: any) {\n try {\n this._tapError.call(this._context, err);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.error(err);\n }\n\n _complete() {\n try {\n this._tapComplete.call(this._context, );\n } catch (err) {\n this.destination.error(err);\n return;\n }\n return this.destination.complete();\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\n\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\n\nimport { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';\n\nexport interface ThrottleConfig {\n leading?: boolean;\n trailing?: boolean;\n}\n\nexport const defaultThrottleConfig: ThrottleConfig = {\n leading: true,\n trailing: false\n};\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for a duration determined by another Observable, then repeats this\n * process.\n *\n * It's like {@link throttleTime}, but the silencing\n * duration is determined by a second Observable.\n *\n * ![](throttle.png)\n *\n * `throttle` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled by calling the `durationSelector` function with the source value,\n * which returns the \"duration\" Observable. When the duration Observable emits a\n * value or completes, the timer is disabled, and this process repeats for the\n * next source value.\n *\n * ## Example\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { throttle } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttle(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param {function(value: T): SubscribableOrPromise} durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration for each source value, returned as an Observable or a Promise.\n * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults\n * to `{ leading: true, trailing: false }`.\n * @return {Observable} An Observable that performs the throttle operation to\n * limit the rate of emissions from the source.\n * @method throttle\n * @owner Observable\n */\nexport function throttle(durationSelector: (value: T) => SubscribableOrPromise,\n config: ThrottleConfig = defaultThrottleConfig): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));\n}\n\nclass ThrottleOperator implements Operator {\n constructor(private durationSelector: (value: T) => SubscribableOrPromise,\n private leading: boolean,\n private trailing: boolean) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(\n new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)\n );\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc\n * @ignore\n * @extends {Ignored}\n */\nclass ThrottleSubscriber extends OuterSubscriber {\n private _throttled: Subscription;\n private _sendValue: T;\n private _hasValue = false;\n\n constructor(protected destination: Subscriber,\n private durationSelector: (value: T) => SubscribableOrPromise,\n private _leading: boolean,\n private _trailing: boolean) {\n super(destination);\n }\n\n protected _next(value: T): void {\n this._hasValue = true;\n this._sendValue = value;\n\n if (!this._throttled) {\n if (this._leading) {\n this.send();\n } else {\n this.throttle(value);\n }\n }\n }\n\n private send() {\n const { _hasValue, _sendValue } = this;\n if (_hasValue) {\n this.destination.next(_sendValue);\n this.throttle(_sendValue);\n }\n this._hasValue = false;\n this._sendValue = null;\n }\n\n private throttle(value: T): void {\n const duration = this.tryDurationSelector(value);\n if (!!duration) {\n this.add(this._throttled = subscribeToResult(this, duration));\n }\n }\n\n private tryDurationSelector(value: T): SubscribableOrPromise {\n try {\n return this.durationSelector(value);\n } catch (err) {\n this.destination.error(err);\n return null;\n }\n }\n\n private throttlingDone() {\n const { _throttled, _trailing } = this;\n if (_throttled) {\n _throttled.unsubscribe();\n }\n this._throttled = null;\n\n if (_trailing) {\n this.send();\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.throttlingDone();\n }\n\n notifyComplete(): void {\n this.throttlingDone();\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { ThrottleConfig, defaultThrottleConfig } from './throttle';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for `duration` milliseconds, then repeats this process.\n *\n * Lets a value pass, then ignores source values for the\n * next `duration` milliseconds.\n *\n * ![](throttleTime.png)\n *\n * `throttleTime` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled. After `duration` milliseconds (or the time unit determined\n * internally by the optional `scheduler`) has passed, the timer is disabled,\n * and this process repeats for the next source value. Optionally takes a\n * {@link SchedulerLike} for managing timers.\n *\n * ## Examples\n *\n * #### Limit click rate\n *\n * Emit clicks at a rate of at most one click per second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { throttleTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttleTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * #### Double Click\n *\n * The following example only emits clicks which happen within a subsequent\n * delay of 400ms of the previous click. This for example can emulate a double\n * click. It makes use of the `trailing` parameter of the throttle configuration.\n *\n * ```ts\n * import { fromEvent, asyncScheduler } from 'rxjs';\n * import { throttleTime, withLatestFrom } from 'rxjs/operators';\n *\n * // defaultThottleConfig = { leading: true, trailing: false }\n * const throttleConfig = {\n * leading: false,\n * trailing: true\n * }\n *\n * const click = fromEvent(document, 'click');\n * const doubleClick = click.pipe(\n * throttleTime(400, asyncScheduler, throttleConfig)\n * );\n *\n * doubleClick.subscribe((throttleValue: Event) => {\n * console.log(`Double-clicked! Timestamp: ${throttleValue.timeStamp}`);\n * });\n * ```\n *\n * If you enable the `leading` parameter in this example, the output would be the primary click and\n * the double click, but restricts additional clicks within 400ms.\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param {number} duration Time to wait before emitting another value after\n * emitting the last value, measured in milliseconds or the time unit determined\n * internally by the optional `scheduler`.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the throttling.\n * @param {Object} config a configuration object to define `leading` and\n * `trailing` behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return {Observable} An Observable that performs the throttle operation to\n * limit the rate of emissions from the source.\n * @method throttleTime\n * @owner Observable\n */\nexport function throttleTime(duration: number,\n scheduler: SchedulerLike = async,\n config: ThrottleConfig = defaultThrottleConfig): MonoTypeOperatorFunction {\n return (source: Observable) => source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));\n}\n\nclass ThrottleTimeOperator implements Operator {\n constructor(private duration: number,\n private scheduler: SchedulerLike,\n private leading: boolean,\n private trailing: boolean) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(\n new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)\n );\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass ThrottleTimeSubscriber extends Subscriber {\n private throttled: Subscription;\n private _hasTrailingValue: boolean = false;\n private _trailingValue: T = null;\n\n constructor(destination: Subscriber,\n private duration: number,\n private scheduler: SchedulerLike,\n private leading: boolean,\n private trailing: boolean) {\n super(destination);\n }\n\n protected _next(value: T) {\n if (this.throttled) {\n if (this.trailing) {\n this._trailingValue = value;\n this._hasTrailingValue = true;\n }\n } else {\n this.add(this.throttled = this.scheduler.schedule>(dispatchNext, this.duration, { subscriber: this }));\n if (this.leading) {\n this.destination.next(value);\n } else if (this.trailing) {\n this._trailingValue = value;\n this._hasTrailingValue = true;\n }\n }\n }\n\n protected _complete() {\n if (this._hasTrailingValue) {\n this.destination.next(this._trailingValue);\n this.destination.complete();\n } else {\n this.destination.complete();\n }\n }\n\n clearThrottle() {\n const throttled = this.throttled;\n if (throttled) {\n if (this.trailing && this._hasTrailingValue) {\n this.destination.next(this._trailingValue);\n this._trailingValue = null;\n this._hasTrailingValue = false;\n }\n throttled.unsubscribe();\n this.remove(throttled);\n this.throttled = null;\n }\n }\n}\n\ninterface DispatchArg {\n subscriber: ThrottleTimeSubscriber;\n}\n\nfunction dispatchNext(arg: DispatchArg) {\n const { subscriber } = arg;\n subscriber.clearThrottle();\n}\n","\nimport { Observable } from '../Observable';\nimport { async } from '../scheduler/async';\nimport { SchedulerLike, OperatorFunction } from '../types';\nimport { scan } from './scan';\nimport { defer } from '../observable/defer';\nimport { map } from './map';\n\n/**\n *\n * Emits an object containing the current value, and the time that has\n * passed between emitting the current value and the previous value, which is\n * calculated by using the provided `scheduler`'s `now()` method to retrieve\n * the current time at each emission, then calculating the difference. The `scheduler`\n * defaults to {@link asyncScheduler}, so by default, the `interval` will be in\n * milliseconds.\n *\n * Convert an Observable that emits items into one that\n * emits indications of the amount of time elapsed between those emissions.\n *\n * ![](timeinterval.png)\n *\n * ## Examples\n * Emit inteval between current value with the last value\n *\n * ```ts\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeinterval())\n * .subscribe(\n * value => console.log(value),\n * err => console.log(err),\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n * value => console.log(value),\n * err => console.log(err),\n * );\n *\n * // NOTE: The values will never be this precise,\n * // intervals created with `interval` or `setInterval`\n * // are non-deterministic.\n *\n * // {value: 0, interval: 1000}\n * // {value: 1, interval: 1000}\n * // {value: 2, interval: 1000}\n * ```\n *\n * @param {SchedulerLike} [scheduler] Scheduler used to get the current time.\n * @return {Observable<{ interval: number, value: T }>} Observable that emit infomation about value and interval\n * @method timeInterval\n */\nexport function timeInterval(scheduler: SchedulerLike = async): OperatorFunction> {\n return (source: Observable) => defer(() => {\n return source.pipe(\n // TODO(benlesh): correct these typings.\n scan(\n ({ current }, value) => ({ value, current: scheduler.now(), last: current }),\n { current: scheduler.now(), value: undefined, last: undefined }\n ) as any,\n map>(({ current, last, value }) => new TimeInterval(value, current - last)),\n );\n });\n}\n\n// TODO(benlesh): make this an interface, export the interface, but not the implemented class,\n// there's no reason users should be manually creating this type.\n\n/**\n * @deprecated exposed API, use as interface only.\n */\nexport class TimeInterval {\n constructor(public value: T, public interval: number) {}\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { isDate } from '../util/isDate';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function timeoutWith(due: number | Date, withObservable: ObservableInput, scheduler?: SchedulerLike): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n *\n * Errors if Observable does not emit a value in given time span, in case of which\n * subscribes to the second Observable.\n *\n * It's a version of `timeout` operator that let's you specify fallback Observable.\n *\n * ![](timeoutWith.png)\n *\n * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,\n * still accepting as a first argument either a number or a Date, which control - respectively -\n * when values of source Observable should be emitted or when it should complete.\n *\n * The only difference is that it accepts a second, required parameter. This parameter\n * should be an Observable which will be subscribed when source Observable fails any timeout check.\n * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting\n * values from second Observable. Note that this fallback Observable is not checked for timeouts\n * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second\n * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that\n * stream completes, it completes as well.\n *\n * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided\n * here - as a third, optional parameter. It still is used to schedule timeout checks and -\n * as a consequence - when second Observable will be subscribed, since subscription happens\n * immediately after failing check.\n *\n * ## Example\n * Add fallback observable\n * ```ts\n * import { intrerval } from 'rxjs';\n * import { timeoutWith } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const minutes = interval(60 * 1000);\n *\n * seconds.pipe(timeoutWith(900, minutes))\n * .subscribe(\n * value => console.log(value), // After 900ms, will start emitting `minutes`,\n * // since first value of `seconds` will not arrive fast enough.\n * err => console.log(err), // Would be called after 900ms in case of `timeout`,\n * // but here will never be called.\n * );\n * ```\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {Observable} withObservable Observable which will be subscribed if source fails timeout check.\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable\n * passed as a second parameter.\n * @method timeoutWith\n * @owner Observable\n */\nexport function timeoutWith(due: number | Date,\n withObservable: ObservableInput,\n scheduler: SchedulerLike = async): OperatorFunction {\n return (source: Observable) => {\n let absoluteTimeout = isDate(due);\n let waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);\n return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));\n };\n}\n\nclass TimeoutWithOperator implements Operator {\n constructor(private waitFor: number,\n private absoluteTimeout: boolean,\n private withObservable: ObservableInput,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber, source: any): TeardownLogic {\n return source.subscribe(new TimeoutWithSubscriber(\n subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TimeoutWithSubscriber extends OuterSubscriber {\n\n private action: SchedulerAction> = null;\n\n constructor(destination: Subscriber,\n private absoluteTimeout: boolean,\n private waitFor: number,\n private withObservable: ObservableInput,\n private scheduler: SchedulerLike) {\n super(destination);\n this.scheduleTimeout();\n }\n\n private static dispatchTimeout(subscriber: TimeoutWithSubscriber): void {\n const { withObservable } = subscriber;\n ( subscriber)._unsubscribeAndRecycle();\n subscriber.add(subscribeToResult(subscriber, withObservable));\n }\n\n private scheduleTimeout(): void {\n const { action } = this;\n if (action) {\n // Recycle the action if we've already scheduled one. All the production\n // Scheduler Actions mutate their state/delay time and return themeselves.\n // VirtualActions are immutable, so they create and return a clone. In this\n // case, we need to set the action reference to the most recent VirtualAction,\n // to ensure that's the one we clone from next time.\n this.action = (>> action.schedule(this, this.waitFor));\n } else {\n this.add(this.action = (>> this.scheduler.schedule>(\n TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this\n )));\n }\n }\n\n protected _next(value: T): void {\n if (!this.absoluteTimeout) {\n this.scheduleTimeout();\n }\n super._next(value);\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.action = null;\n this.scheduler = null;\n this.withObservable = null;\n }\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { TimeoutError } from '../util/TimeoutError';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { timeoutWith } from './timeoutWith';\nimport { throwError } from '../observable/throwError';\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * Timeouts on Observable that doesn't emit values fast enough.\n *\n * ![](timeout.png)\n *\n * `timeout` operator accepts as an argument either a number or a Date.\n *\n * If number was provided, it returns an Observable that behaves like a source\n * Observable, unless there is a period of time where there is no value emitted.\n * So if you provide `100` as argument and first value comes after 50ms from\n * the moment of subscription, this value will be simply re-emitted by the resulting\n * Observable. If however after that 100ms passes without a second value being emitted,\n * stream will end with an error and source Observable will be unsubscribed.\n * These checks are performed throughout whole lifecycle of Observable - from the moment\n * it was subscribed to, until it completes or errors itself. Thus every value must be\n * emitted within specified period since previous value.\n *\n * If provided argument was Date, returned Observable behaves differently. It throws\n * if Observable did not complete before provided Date. This means that periods between\n * emission of particular values do not matter in this case. If Observable did not complete\n * before provided Date, source Observable will be unsubscribed. Other than that, resulting\n * stream behaves just as source Observable.\n *\n * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)\n * when returned Observable will check if source stream emitted value or completed.\n *\n * ## Examples\n * Check if ticks are emitted within certain timespan\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeout(1100)) // Let's use bigger timespan to be safe,\n * // since `interval` might fire a bit later then scheduled.\n * .subscribe(\n * value => console.log(value), // Will emit numbers just as regular `interval` would.\n * err => console.log(err), // Will never be called.\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n * value => console.log(value), // Will never be called.\n * err => console.log(err), // Will emit error before even first value is emitted,\n * // since it did not arrive within 900ms period.\n * );\n * ```\n *\n * Use Date to check if Observable completed\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(\n * timeout(new Date(\"December 17, 2020 03:24:00\")),\n * )\n * .subscribe(\n * value => console.log(value), // Will emit values as regular `interval` would\n * // until December 17, 2020 at 03:24:00.\n * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,\n * // since Observable did not complete by then.\n * );\n * ```\n * @see {@link timeoutWith}\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable} Observable that mirrors behaviour of source, unless timeout checks fail.\n * @method timeout\n * @owner Observable\n */\nexport function timeout(due: number | Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction {\n return timeoutWith(due, throwError(new TimeoutError()), scheduler);\n}\n","\nimport { async } from '../scheduler/async';\nimport { OperatorFunction, SchedulerLike, Timestamp as TimestampInterface } from '../types';\nimport { map } from './map';\n\n/**\n * Attaches a timestamp to each item emitted by an observable indicating when it was emitted\n *\n * The `timestamp` operator maps the *source* observable stream to an object of type\n * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value\n * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By\n * default it uses the *async* scheduler which simply returns `Date.now()` (milliseconds since 1970/01/01\n * 00:00:00:000) and therefore is of type `number`.\n *\n * ![](timestamp.png)\n *\n * ## Example\n *\n * In this example there is a timestamp attached to the documents click event.\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { timestamp } from 'rxjs/operators';\n *\n * const clickWithTimestamp = fromEvent(document, 'click').pipe(\n * timestamp()\n * );\n *\n * // Emits data of type {value: MouseEvent, timestamp: number}\n * clickWithTimestamp.subscribe(data => {\n * console.log(data);\n * });\n * ```\n *\n * @param scheduler\n * @return {Observable>|WebSocketSubject|Observable}\n * @method timestamp\n * @owner Observable\n */\nexport function timestamp(scheduler: SchedulerLike = async): OperatorFunction> {\n return map((value: T) => new Timestamp(value, scheduler.now()));\n // return (source: Observable) => source.lift(new TimestampOperator(scheduler));\n}\n\nexport class Timestamp implements TimestampInterface {\n constructor(public value: T, public timestamp: number) {\n }\n}\n","import { reduce } from './reduce';\nimport { OperatorFunction } from '../types';\n\nfunction toArrayReducer(arr: T[], item: T, index: number) {\n if (index === 0) {\n return [item];\n }\n arr.push(item);\n return arr;\n}\n\nexport function toArray(): OperatorFunction {\n return reduce(toArrayReducer, [] as T[]);\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\nimport { Subject } from '../Subject';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { Operator } from '../Operator';\n\n/**\n * Branch out the source Observable values as a nested Observable whenever\n * `windowBoundaries` emits.\n *\n * It's like {@link buffer}, but emits a nested Observable\n * instead of an array.\n *\n * ![](window.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping\n * windows. It emits the current window and opens a new one whenever the\n * Observable `windowBoundaries` emits an item. Because each window is an\n * Observable, the output is a higher-order Observable.\n *\n * ## Example\n * In every window of 1 second each, emit at most 2 click events\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { window, mergeAll, map, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const sec = interval(1000);\n * const result = clicks.pipe(\n * window(sec),\n * map(win => win.pipe(take(2))), // each window has at most 2 emissions\n * mergeAll(), // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link buffer}\n *\n * @param {Observable} windowBoundaries An Observable that completes the\n * previous window and starts a new window.\n * @return {Observable>} An Observable of windows, which are\n * Observables emitting values of the source Observable.\n * @method window\n * @owner Observable\n */\nexport function window(windowBoundaries: Observable): OperatorFunction> {\n return function windowOperatorFunction(source: Observable) {\n return source.lift(new WindowOperator(windowBoundaries));\n };\n}\n\nclass WindowOperator implements Operator> {\n\n constructor(private windowBoundaries: Observable) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n const windowSubscriber = new WindowSubscriber(subscriber);\n const sourceSubscription = source.subscribe(windowSubscriber);\n if (!sourceSubscription.closed) {\n windowSubscriber.add(subscribeToResult(windowSubscriber, this.windowBoundaries));\n }\n return sourceSubscription;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowSubscriber extends OuterSubscriber {\n\n private window: Subject = new Subject();\n\n constructor(destination: Subscriber>) {\n super(destination);\n destination.next(this.window);\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.openWindow();\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this._error(error);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n this._complete();\n }\n\n protected _next(value: T): void {\n this.window.next(value);\n }\n\n protected _error(err: any): void {\n this.window.error(err);\n this.destination.error(err);\n }\n\n protected _complete(): void {\n this.window.complete();\n this.destination.complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.window = null;\n }\n\n private openWindow(): void {\n const prevWindow = this.window;\n if (prevWindow) {\n prevWindow.complete();\n }\n const destination = this.destination;\n const newWindow = this.window = new Subject();\n destination.next(newWindow);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable with each\n * nested Observable emitting at most `windowSize` values.\n *\n * It's like {@link bufferCount}, but emits a nested\n * Observable instead of an array.\n *\n * ![](windowCount.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows every `startWindowEvery`\n * items, each containing no more than `windowSize` items. When the source\n * Observable completes or encounters an error, the output Observable emits\n * the current window and propagates the notification from the source\n * Observable. If `startWindowEvery` is not provided, then new windows are\n * started immediately at the start of the source and when each window completes\n * with size `windowSize`.\n *\n * ## Examples\n * Ignore every 3rd click event, starting from the first one\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowCount, map, mergeAll, skip } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(3),\n * map(win => win.pipe(skip(1))), // skip first of every 3 clicks\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Ignore every 3rd click event, starting from the third one\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowCount, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(2, 3),\n * mergeAll(), // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferCount}\n *\n * @param {number} windowSize The maximum number of values emitted by each\n * window.\n * @param {number} [startWindowEvery] Interval at which to start a new window.\n * For example if `startWindowEvery` is `2`, then a new window will be started\n * on every other value from the source. A new window is started at the\n * beginning of the source by default.\n * @return {Observable>} An Observable of windows, which in turn\n * are Observable of values.\n * @method windowCount\n * @owner Observable\n */\nexport function windowCount(windowSize: number,\n startWindowEvery: number = 0): OperatorFunction> {\n return function windowCountOperatorFunction(source: Observable) {\n return source.lift(new WindowCountOperator(windowSize, startWindowEvery));\n };\n}\n\nclass WindowCountOperator implements Operator> {\n\n constructor(private windowSize: number,\n private startWindowEvery: number) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowCountSubscriber extends Subscriber {\n private windows: Subject[] = [ new Subject() ];\n private count: number = 0;\n\n constructor(protected destination: Subscriber>,\n private windowSize: number,\n private startWindowEvery: number) {\n super(destination);\n destination.next(this.windows[0]);\n }\n\n protected _next(value: T) {\n const startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;\n const destination = this.destination;\n const windowSize = this.windowSize;\n const windows = this.windows;\n const len = windows.length;\n\n for (let i = 0; i < len && !this.closed; i++) {\n windows[i].next(value);\n }\n const c = this.count - windowSize + 1;\n if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {\n windows.shift().complete();\n }\n if (++this.count % startWindowEvery === 0 && !this.closed) {\n const window = new Subject();\n windows.push(window);\n destination.next(window);\n }\n }\n\n protected _error(err: any) {\n const windows = this.windows;\n if (windows) {\n while (windows.length > 0 && !this.closed) {\n windows.shift().error(err);\n }\n }\n this.destination.error(err);\n }\n\n protected _complete() {\n const windows = this.windows;\n if (windows) {\n while (windows.length > 0 && !this.closed) {\n windows.shift().complete();\n }\n }\n this.destination.complete();\n }\n\n protected _unsubscribe() {\n this.count = 0;\n this.windows = null;\n }\n}\n","import { Subject } from '../Subject';\nimport { Operator } from '../Operator';\nimport { async } from '../scheduler/async';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { isNumeric } from '../util/isNumeric';\nimport { isScheduler } from '../util/isScheduler';\nimport { OperatorFunction, SchedulerLike, SchedulerAction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable periodically\n * in time.\n *\n * It's like {@link bufferTime}, but emits a nested\n * Observable instead of an array.\n *\n * ![](windowTime.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable starts a new window periodically, as\n * determined by the `windowCreationInterval` argument. It emits each window\n * after a fixed timespan, specified by the `windowTimeSpan` argument. When the\n * source Observable completes or encounters an error, the output Observable\n * emits the current window and propagates the notification from the source\n * Observable. If `windowCreationInterval` is not provided, the output\n * Observable starts a new window when the previous window of duration\n * `windowTimeSpan` completes. If `maxWindowCount` is provided, each window\n * will emit at most fixed number of values. Window will complete immediately\n * after emitting last value and next one still will open as specified by\n * `windowTimeSpan` and `windowCreationInterval` arguments.\n *\n * ## Examples\n * In every window of 1 second each, emit at most 2 click events\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000),\n * map(win => win.pipe(take(2))), // each window has at most 2 emissions\n * mergeAll(), // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000),\n * map(win => win.pipe(take(2))), // each window has at most 2 emissions\n * mergeAll(), // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Same as example above but with maxWindowCount instead of take\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { windowTime, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000, 2), // each window has still at most 2 emissions\n * mergeAll(), // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferTime}\n *\n * @param {number} windowTimeSpan The amount of time to fill each window.\n * @param {number} [windowCreationInterval] The interval at which to start new\n * windows.\n * @param {number} [maxWindowSize=Number.POSITIVE_INFINITY] Max number of\n * values each window can emit before completion.\n * @param {SchedulerLike} [scheduler=async] The scheduler on which to schedule the\n * intervals that determine window boundaries.\n * @return {Observable>} An observable of windows, which in turn\n * are Observables.\n * @method windowTime\n * @owner Observable\n */\nexport function windowTime(windowTimeSpan: number,\n scheduler?: SchedulerLike): OperatorFunction>;\nexport function windowTime(windowTimeSpan: number,\n windowCreationInterval: number,\n scheduler?: SchedulerLike): OperatorFunction>;\nexport function windowTime(windowTimeSpan: number,\n windowCreationInterval: number,\n maxWindowSize: number,\n scheduler?: SchedulerLike): OperatorFunction>;\n\nexport function windowTime(windowTimeSpan: number): OperatorFunction> {\n let scheduler: SchedulerLike = async;\n let windowCreationInterval: number = null;\n let maxWindowSize: number = Number.POSITIVE_INFINITY;\n\n if (isScheduler(arguments[3])) {\n scheduler = arguments[3];\n }\n\n if (isScheduler(arguments[2])) {\n scheduler = arguments[2];\n } else if (isNumeric(arguments[2])) {\n maxWindowSize = arguments[2];\n }\n\n if (isScheduler(arguments[1])) {\n scheduler = arguments[1];\n } else if (isNumeric(arguments[1])) {\n windowCreationInterval = arguments[1];\n }\n\n return function windowTimeOperatorFunction(source: Observable) {\n return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));\n };\n}\n\nclass WindowTimeOperator implements Operator> {\n\n constructor(private windowTimeSpan: number,\n private windowCreationInterval: number | null,\n private maxWindowSize: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new WindowTimeSubscriber(\n subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler\n ));\n }\n}\n\ninterface CreationState {\n windowTimeSpan: number;\n windowCreationInterval: number;\n subscriber: WindowTimeSubscriber;\n scheduler: SchedulerLike;\n}\n\ninterface TimeSpanOnlyState {\n window: CountedSubject;\n windowTimeSpan: number;\n subscriber: WindowTimeSubscriber;\n }\n\ninterface CloseWindowContext {\n action: SchedulerAction>;\n subscription: Subscription;\n}\n\ninterface CloseState {\n subscriber: WindowTimeSubscriber;\n window: CountedSubject;\n context: CloseWindowContext;\n}\n\nclass CountedSubject extends Subject {\n private _numberOfNextedValues: number = 0;\n\n next(value?: T): void {\n this._numberOfNextedValues++;\n super.next(value);\n }\n\n get numberOfNextedValues(): number {\n return this._numberOfNextedValues;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowTimeSubscriber extends Subscriber {\n private windows: CountedSubject[] = [];\n\n constructor(protected destination: Subscriber>,\n private windowTimeSpan: number,\n private windowCreationInterval: number | null,\n private maxWindowSize: number,\n private scheduler: SchedulerLike) {\n super(destination);\n\n const window = this.openWindow();\n if (windowCreationInterval !== null && windowCreationInterval >= 0) {\n const closeState: CloseState = { subscriber: this, window, context: null };\n const creationState: CreationState = { windowTimeSpan, windowCreationInterval, subscriber: this, scheduler };\n this.add(scheduler.schedule>(dispatchWindowClose, windowTimeSpan, closeState));\n this.add(scheduler.schedule>(dispatchWindowCreation, windowCreationInterval, creationState));\n } else {\n const timeSpanOnlyState: TimeSpanOnlyState = { subscriber: this, window, windowTimeSpan };\n this.add(scheduler.schedule>(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));\n }\n }\n\n protected _next(value: T): void {\n const windows = this.windows;\n const len = windows.length;\n for (let i = 0; i < len; i++) {\n const window = windows[i];\n if (!window.closed) {\n window.next(value);\n if (window.numberOfNextedValues >= this.maxWindowSize) {\n this.closeWindow(window);\n }\n }\n }\n }\n\n protected _error(err: any): void {\n const windows = this.windows;\n while (windows.length > 0) {\n windows.shift().error(err);\n }\n this.destination.error(err);\n }\n\n protected _complete(): void {\n const windows = this.windows;\n while (windows.length > 0) {\n const window = windows.shift();\n if (!window.closed) {\n window.complete();\n }\n }\n this.destination.complete();\n }\n\n public openWindow(): CountedSubject {\n const window = new CountedSubject();\n this.windows.push(window);\n const destination = this.destination;\n destination.next(window);\n return window;\n }\n\n public closeWindow(window: CountedSubject): void {\n window.complete();\n const windows = this.windows;\n windows.splice(windows.indexOf(window), 1);\n }\n}\n\nfunction dispatchWindowTimeSpanOnly(this: SchedulerAction>, state: TimeSpanOnlyState): void {\n const { subscriber, windowTimeSpan, window } = state;\n if (window) {\n subscriber.closeWindow(window);\n }\n state.window = subscriber.openWindow();\n this.schedule(state, windowTimeSpan);\n}\n\nfunction dispatchWindowCreation(this: SchedulerAction>, state: CreationState): void {\n const { windowTimeSpan, subscriber, scheduler, windowCreationInterval } = state;\n const window = subscriber.openWindow();\n const action = this;\n let context: CloseWindowContext = { action, subscription: null };\n const timeSpanState: CloseState = { subscriber, window, context };\n context.subscription = scheduler.schedule>(dispatchWindowClose, windowTimeSpan, timeSpanState);\n action.add(context.subscription);\n action.schedule(state, windowCreationInterval);\n}\n\nfunction dispatchWindowClose(state: CloseState): void {\n const { subscriber, window, context } = state;\n if (context && context.action && context.subscription) {\n context.action.remove(context.subscription);\n }\n subscriber.closeWindow(window);\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable starting from\n * an emission from `openings` and ending when the output of `closingSelector`\n * emits.\n *\n * It's like {@link bufferToggle}, but emits a nested\n * Observable instead of an array.\n *\n * ![](windowToggle.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows that contain those items\n * emitted by the source Observable between the time when the `openings`\n * Observable emits an item and when the Observable returned by\n * `closingSelector` emits an item.\n *\n * ## Example\n * Every other second, emit the click events from the next 500ms\n * ```ts\n * import { fromEvent, interval, EMPTY } from 'rxjs';\n * import { windowToggle, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const result = clicks.pipe(\n * windowToggle(openings, i => i % 2 ? interval(500) : EMPTY),\n * mergeAll()\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowWhen}\n * @see {@link bufferToggle}\n *\n * @param {Observable} openings An observable of notifications to start new\n * windows.\n * @param {function(value: O): Observable} closingSelector A function that takes\n * the value emitted by the `openings` observable and returns an Observable,\n * which, when it emits (either `next` or `complete`), signals that the\n * associated window should complete.\n * @return {Observable>} An observable of windows, which in turn\n * are Observables.\n * @method windowToggle\n * @owner Observable\n */\nexport function windowToggle(openings: Observable,\n closingSelector: (openValue: O) => Observable): OperatorFunction> {\n return (source: Observable) => source.lift(new WindowToggleOperator(openings, closingSelector));\n}\n\nclass WindowToggleOperator implements Operator> {\n\n constructor(private openings: Observable,\n private closingSelector: (openValue: O) => Observable) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new WindowToggleSubscriber(\n subscriber, this.openings, this.closingSelector\n ));\n }\n}\n\ninterface WindowContext {\n window: Subject;\n subscription: Subscription;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowToggleSubscriber extends OuterSubscriber {\n private contexts: WindowContext[] = [];\n private openSubscription: Subscription;\n\n constructor(destination: Subscriber>,\n private openings: Observable,\n private closingSelector: (openValue: O) => Observable) {\n super(destination);\n this.add(this.openSubscription = subscribeToResult(this, openings, openings as any));\n }\n\n protected _next(value: T) {\n const { contexts } = this;\n if (contexts) {\n const len = contexts.length;\n for (let i = 0; i < len; i++) {\n contexts[i].window.next(value);\n }\n }\n }\n\n protected _error(err: any) {\n\n const { contexts } = this;\n this.contexts = null;\n\n if (contexts) {\n const len = contexts.length;\n let index = -1;\n\n while (++index < len) {\n const context = contexts[index];\n context.window.error(err);\n context.subscription.unsubscribe();\n }\n }\n\n super._error(err);\n }\n\n protected _complete() {\n const { contexts } = this;\n this.contexts = null;\n if (contexts) {\n const len = contexts.length;\n let index = -1;\n while (++index < len) {\n const context = contexts[index];\n context.window.complete();\n context.subscription.unsubscribe();\n }\n }\n super._complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { contexts } = this;\n this.contexts = null;\n if (contexts) {\n const len = contexts.length;\n let index = -1;\n while (++index < len) {\n const context = contexts[index];\n context.window.unsubscribe();\n context.subscription.unsubscribe();\n }\n }\n }\n\n notifyNext(outerValue: any, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n\n if (outerValue === this.openings) {\n let closingNotifier;\n try {\n const { closingSelector } = this;\n closingNotifier = closingSelector(innerValue);\n } catch (e) {\n return this.error(e);\n }\n\n const window = new Subject();\n const subscription = new Subscription();\n const context = { window, subscription };\n this.contexts.push(context);\n const innerSubscription = subscribeToResult(this, closingNotifier, context as any);\n\n if (innerSubscription.closed) {\n this.closeWindow(this.contexts.length - 1);\n } else {\n (innerSubscription).context = context;\n subscription.add(innerSubscription);\n }\n\n this.destination.next(window);\n } else {\n this.closeWindow(this.contexts.indexOf(outerValue));\n }\n }\n\n notifyError(err: any): void {\n this.error(err);\n }\n\n notifyComplete(inner: Subscription): void {\n if (inner !== this.openSubscription) {\n this.closeWindow(this.contexts.indexOf(( inner).context));\n }\n }\n\n private closeWindow(index: number): void {\n if (index === -1) {\n return;\n }\n\n const { contexts } = this;\n const context = contexts[index];\n const { window, subscription } = context;\n contexts.splice(index, 1);\n window.complete();\n subscription.unsubscribe();\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { OperatorFunction } from '../types';\n\n/**\n * Branch out the source Observable values as a nested Observable using a\n * factory function of closing Observables to determine when to start a new\n * window.\n *\n * It's like {@link bufferWhen}, but emits a nested\n * Observable instead of an array.\n *\n * ![](windowWhen.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping windows.\n * It emits the current window and opens a new one whenever the Observable\n * produced by the specified `closingSelector` function emits an item. The first\n * window is opened immediately when subscribing to the output Observable.\n *\n * ## Example\n * Emit only the first two clicks events in every window of [1-5] random seconds\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { windowWhen, map, mergeAll, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowWhen(() => interval(1000 + Math.random() * 4000)),\n * map(win => win.pipe(take(2))), // each window has at most 2 emissions\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link bufferWhen}\n *\n * @param {function(): Observable} closingSelector A function that takes no\n * arguments and returns an Observable that signals (on either `next` or\n * `complete`) when to close the previous window and start a new one.\n * @return {Observable>} An observable of windows, which in turn\n * are Observables.\n * @method windowWhen\n * @owner Observable\n */\nexport function windowWhen(closingSelector: () => Observable): OperatorFunction> {\n return function windowWhenOperatorFunction(source: Observable) {\n return source.lift(new WindowOperator(closingSelector));\n };\n}\n\nclass WindowOperator implements Operator> {\n constructor(private closingSelector: () => Observable) {\n }\n\n call(subscriber: Subscriber>, source: any): any {\n return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WindowSubscriber extends OuterSubscriber {\n private window: Subject;\n private closingNotification: Subscription;\n\n constructor(protected destination: Subscriber>,\n private closingSelector: () => Observable) {\n super(destination);\n this.openWindow();\n }\n\n notifyNext(outerValue: T, innerValue: any,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.openWindow(innerSub);\n }\n\n notifyError(error: any, innerSub: InnerSubscriber): void {\n this._error(error);\n }\n\n notifyComplete(innerSub: InnerSubscriber): void {\n this.openWindow(innerSub);\n }\n\n protected _next(value: T): void {\n this.window.next(value);\n }\n\n protected _error(err: any): void {\n this.window.error(err);\n this.destination.error(err);\n this.unsubscribeClosingNotification();\n }\n\n protected _complete(): void {\n this.window.complete();\n this.destination.complete();\n this.unsubscribeClosingNotification();\n }\n\n private unsubscribeClosingNotification(): void {\n if (this.closingNotification) {\n this.closingNotification.unsubscribe();\n }\n }\n\n private openWindow(innerSub: InnerSubscriber = null): void {\n if (innerSub) {\n this.remove(innerSub);\n innerSub.unsubscribe();\n }\n\n const prevWindow = this.window;\n if (prevWindow) {\n prevWindow.complete();\n }\n\n const window = this.window = new Subject();\n this.destination.next(window);\n\n let closingNotifier;\n try {\n const { closingSelector } = this;\n closingNotifier = closingSelector();\n } catch (e) {\n this.destination.error(e);\n this.window.error(e);\n return;\n }\n this.add(this.closingNotification = subscribeToResult(this, closingNotifier));\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function withLatestFrom(project: (v1: T) => R): OperatorFunction;\nexport function withLatestFrom, R>(source2: O2, project: (v1: T, v2: ObservedValueOf) => R): OperatorFunction;\nexport function withLatestFrom, O3 extends ObservableInput, R>(v2: O2, v3: O3, project: (v1: T, v2: ObservedValueOf, v3: ObservedValueOf) => R): OperatorFunction;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput, R>(v2: O2, v3: O3, v4: O4, project: (v1: T, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf) => R): OperatorFunction;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, R>(v2: O2, v3: O3, v4: O4, v5: O5, project: (v1: T, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf) => R): OperatorFunction;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput, R>(v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, project: (v1: T, v2: ObservedValueOf, v3: ObservedValueOf, v4: ObservedValueOf, v5: ObservedValueOf, v6: ObservedValueOf) => R): OperatorFunction;\nexport function withLatestFrom>(source2: O2): OperatorFunction]>;\nexport function withLatestFrom, O3 extends ObservableInput>(v2: O2, v3: O3): OperatorFunction, ObservedValueOf]>;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput>(v2: O2, v3: O3, v4: O4): OperatorFunction, ObservedValueOf, ObservedValueOf]>;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput>(v2: O2, v3: O3, v4: O4, v5: O5): OperatorFunction, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function withLatestFrom, O3 extends ObservableInput, O4 extends ObservableInput, O5 extends ObservableInput, O6 extends ObservableInput>(v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): OperatorFunction, ObservedValueOf, ObservedValueOf, ObservedValueOf, ObservedValueOf]>;\nexport function withLatestFrom(...observables: Array | ((...values: Array) => R)>): OperatorFunction;\nexport function withLatestFrom(array: ObservableInput[]): OperatorFunction;\nexport function withLatestFrom(array: ObservableInput[], project: (...values: Array) => R): OperatorFunction;\n\n/* tslint:enable:max-line-length */\n\n/**\n * Combines the source Observable with other Observables to create an Observable\n * whose values are calculated from the latest values of each, only when the\n * source emits.\n *\n * Whenever the source Observable emits a value, it\n * computes a formula using that value plus the latest values from other input\n * Observables, then emits the output of that formula.\n *\n * ![](withLatestFrom.png)\n *\n * `withLatestFrom` combines each value from the source Observable (the\n * instance) with the latest values from the other input Observables only when\n * the source emits a value, optionally using a `project` function to determine\n * the value to be emitted on the output Observable. All input Observables must\n * emit at least one value before the output Observable will emit a value.\n *\n * ## Example\n * On every click event, emit an array with the latest timer event plus the click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { withLatestFrom } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const result = clicks.pipe(withLatestFrom(timer));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n *\n * @param {ObservableInput} other An input Observable to combine with the source\n * Observable. More than one input Observables may be given as argument.\n * @param {Function} [project] Projection function for combining values\n * together. Receives all values in order of the Observables passed, where the\n * first parameter is a value from the source Observable. (e.g.\n * `a.pipe(withLatestFrom(b, c), map(([a1, b1, c1]) => a1 + b1 + c1))`). If this is not\n * passed, arrays will be emitted on the output Observable.\n * @return {Observable} An Observable of projected values from the most recent\n * values from each input Observable, or an array of the most recent values from\n * each input Observable.\n * @method withLatestFrom\n * @owner Observable\n */\nexport function withLatestFrom(...args: Array | ((...values: Array) => R)>): OperatorFunction {\n return (source: Observable) => {\n let project: any;\n if (typeof args[args.length - 1] === 'function') {\n project = args.pop();\n }\n const observables = []>args;\n return source.lift(new WithLatestFromOperator(observables, project));\n };\n}\n\nclass WithLatestFromOperator implements Operator {\n constructor(private observables: Observable[],\n private project?: (...values: any[]) => Observable) {\n }\n\n call(subscriber: Subscriber, source: any): any {\n return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass WithLatestFromSubscriber extends OuterSubscriber {\n private values: any[];\n private toRespond: number[] = [];\n\n constructor(destination: Subscriber,\n private observables: Observable[],\n private project?: (...values: any[]) => Observable) {\n super(destination);\n const len = observables.length;\n this.values = new Array(len);\n\n for (let i = 0; i < len; i++) {\n this.toRespond.push(i);\n }\n\n for (let i = 0; i < len; i++) {\n let observable = observables[i];\n this.add(subscribeToResult(this, observable, observable, i));\n }\n }\n\n notifyNext(outerValue: T, innerValue: R,\n outerIndex: number, innerIndex: number,\n innerSub: InnerSubscriber): void {\n this.values[outerIndex] = innerValue;\n const toRespond = this.toRespond;\n if (toRespond.length > 0) {\n const found = toRespond.indexOf(outerIndex);\n if (found !== -1) {\n toRespond.splice(found, 1);\n }\n }\n }\n\n notifyComplete() {\n // noop\n }\n\n protected _next(value: T) {\n if (this.toRespond.length === 0) {\n const args = [value, ...this.values];\n if (this.project) {\n this._tryProject(args);\n } else {\n this.destination.next(args);\n }\n }\n }\n\n private _tryProject(args: any[]) {\n let result: any;\n try {\n result = this.project.apply(this, args);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { zip as zipStatic } from '../observable/zip';\nimport { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(project: (v1: T) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, project: (v1: T, v2: T2) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, project: (v1: T, v2: T2, v3: T3) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): OperatorFunction ;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(v2: ObservableInput, v3: ObservableInput, v4: ObservableInput, v5: ObservableInput, v6: ObservableInput): OperatorFunction ;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(...observables: Array | ((...values: Array) => R)>): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(array: Array>): OperatorFunction;\n/** @deprecated Deprecated in favor of static zip. */\nexport function zip(array: Array>, project: (v1: T, ...values: Array) => R): OperatorFunction;\n/* tslint:enable:max-line-length */\n\n/**\n * @deprecated Deprecated in favor of static {@link zip}.\n */\nexport function zip(...observables: Array | ((...values: Array) => R)>): OperatorFunction {\n return function zipOperatorFunction(source: Observable) {\n return source.lift.call(zipStatic(source, ...observables));\n };\n}","import { ZipOperator } from '../observable/zip';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function zipAll(): OperatorFunction, T[]>;\nexport function zipAll(): OperatorFunction;\nexport function zipAll(project: (...values: T[]) => R): OperatorFunction, R>;\nexport function zipAll(project: (...values: Array) => R): OperatorFunction;\n\nexport function zipAll(project?: (...values: Array) => R): OperatorFunction {\n return (source: Observable) => source.lift(new ZipOperator(project));\n}\n","\n/* Operator exports */\nexport { audit } from '../internal/operators/audit';\nexport { auditTime } from '../internal/operators/auditTime';\nexport { buffer } from '../internal/operators/buffer';\nexport { bufferCount } from '../internal/operators/bufferCount';\nexport { bufferTime } from '../internal/operators/bufferTime';\nexport { bufferToggle } from '../internal/operators/bufferToggle';\nexport { bufferWhen } from '../internal/operators/bufferWhen';\nexport { catchError } from '../internal/operators/catchError';\nexport { combineAll } from '../internal/operators/combineAll';\nexport { combineLatest } from '../internal/operators/combineLatest';\nexport { concat } from '../internal/operators/concat';\nexport { concatAll } from '../internal/operators/concatAll';\nexport { concatMap } from '../internal/operators/concatMap';\nexport { concatMapTo } from '../internal/operators/concatMapTo';\nexport { count } from '../internal/operators/count';\nexport { debounce } from '../internal/operators/debounce';\nexport { debounceTime } from '../internal/operators/debounceTime';\nexport { defaultIfEmpty } from '../internal/operators/defaultIfEmpty';\nexport { delay } from '../internal/operators/delay';\nexport { delayWhen } from '../internal/operators/delayWhen';\nexport { dematerialize } from '../internal/operators/dematerialize';\nexport { distinct } from '../internal/operators/distinct';\nexport { distinctUntilChanged } from '../internal/operators/distinctUntilChanged';\nexport { distinctUntilKeyChanged } from '../internal/operators/distinctUntilKeyChanged';\nexport { elementAt } from '../internal/operators/elementAt';\nexport { endWith } from '../internal/operators/endWith';\nexport { every } from '../internal/operators/every';\nexport { exhaust } from '../internal/operators/exhaust';\nexport { exhaustMap } from '../internal/operators/exhaustMap';\nexport { expand } from '../internal/operators/expand';\nexport { filter } from '../internal/operators/filter';\nexport { finalize } from '../internal/operators/finalize';\nexport { find } from '../internal/operators/find';\nexport { findIndex } from '../internal/operators/findIndex';\nexport { first } from '../internal/operators/first';\nexport { groupBy } from '../internal/operators/groupBy';\nexport { ignoreElements } from '../internal/operators/ignoreElements';\nexport { isEmpty } from '../internal/operators/isEmpty';\nexport { last } from '../internal/operators/last';\nexport { map } from '../internal/operators/map';\nexport { mapTo } from '../internal/operators/mapTo';\nexport { materialize } from '../internal/operators/materialize';\nexport { max } from '../internal/operators/max';\nexport { merge } from '../internal/operators/merge';\nexport { mergeAll } from '../internal/operators/mergeAll';\nexport { mergeMap } from '../internal/operators/mergeMap';\nexport { mergeMap as flatMap } from '../internal/operators/mergeMap';\nexport { mergeMapTo } from '../internal/operators/mergeMapTo';\nexport { mergeScan } from '../internal/operators/mergeScan';\nexport { min } from '../internal/operators/min';\nexport { multicast } from '../internal/operators/multicast';\nexport { observeOn } from '../internal/operators/observeOn';\nexport { onErrorResumeNext } from '../internal/operators/onErrorResumeNext';\nexport { pairwise } from '../internal/operators/pairwise';\nexport { partition } from '../internal/operators/partition';\nexport { pluck } from '../internal/operators/pluck';\nexport { publish } from '../internal/operators/publish';\nexport { publishBehavior } from '../internal/operators/publishBehavior';\nexport { publishLast } from '../internal/operators/publishLast';\nexport { publishReplay } from '../internal/operators/publishReplay';\nexport { race } from '../internal/operators/race';\nexport { reduce } from '../internal/operators/reduce';\nexport { repeat } from '../internal/operators/repeat';\nexport { repeatWhen } from '../internal/operators/repeatWhen';\nexport { retry } from '../internal/operators/retry';\nexport { retryWhen } from '../internal/operators/retryWhen';\nexport { refCount } from '../internal/operators/refCount';\nexport { sample } from '../internal/operators/sample';\nexport { sampleTime } from '../internal/operators/sampleTime';\nexport { scan } from '../internal/operators/scan';\nexport { sequenceEqual } from '../internal/operators/sequenceEqual';\nexport { share } from '../internal/operators/share';\nexport { shareReplay } from '../internal/operators/shareReplay';\nexport { single } from '../internal/operators/single';\nexport { skip } from '../internal/operators/skip';\nexport { skipLast } from '../internal/operators/skipLast';\nexport { skipUntil } from '../internal/operators/skipUntil';\nexport { skipWhile } from '../internal/operators/skipWhile';\nexport { startWith } from '../internal/operators/startWith';\nexport { subscribeOn } from '../internal/operators/subscribeOn';\nexport { switchAll } from '../internal/operators/switchAll';\nexport { switchMap } from '../internal/operators/switchMap';\nexport { switchMapTo } from '../internal/operators/switchMapTo';\nexport { take } from '../internal/operators/take';\nexport { takeLast } from '../internal/operators/takeLast';\nexport { takeUntil } from '../internal/operators/takeUntil';\nexport { takeWhile } from '../internal/operators/takeWhile';\nexport { tap } from '../internal/operators/tap';\nexport { throttle } from '../internal/operators/throttle';\nexport { throttleTime } from '../internal/operators/throttleTime';\nexport { throwIfEmpty } from '../internal/operators/throwIfEmpty';\nexport { timeInterval } from '../internal/operators/timeInterval';\nexport { timeout } from '../internal/operators/timeout';\nexport { timeoutWith } from '../internal/operators/timeoutWith';\nexport { timestamp } from '../internal/operators/timestamp';\nexport { toArray } from '../internal/operators/toArray';\nexport { window } from '../internal/operators/window';\nexport { windowCount } from '../internal/operators/windowCount';\nexport { windowTime } from '../internal/operators/windowTime';\nexport { windowToggle } from '../internal/operators/windowToggle';\nexport { windowWhen } from '../internal/operators/windowWhen';\nexport { withLatestFrom } from '../internal/operators/withLatestFrom';\nexport { zip } from '../internal/operators/zip';\nexport { zipAll } from '../internal/operators/zipAll';\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rxjs_1 = require(\"rxjs\");\nconst operators_1 = require(\"rxjs/operators\");\nclass CacheLayer {\n constructor(layer) {\n this.items = new rxjs_1.BehaviorSubject([]);\n this.map = new Map();\n this.name = layer.name;\n this.config = layer.config;\n this.initHook(layer);\n }\n get(name) {\n return this.map.get(name);\n }\n initHook(layer) {\n if (this.config.maxAge) {\n this.onExpireAll(layer);\n }\n }\n onExpireAll(layer) {\n layer.items.forEach(item => this.onExpire(item['key']));\n }\n putItemHook(layerItem) {\n if (this.config.maxAge) {\n this.onExpire(layerItem['key']);\n }\n }\n getItem(key) {\n if (this.map.has(key)) {\n return this.get(key);\n }\n else {\n return null;\n }\n }\n putItem(layerItem) {\n this.map.set(layerItem['key'], layerItem);\n const item = this.get(layerItem['key']);\n const filteredItems = this.items\n .getValue()\n .filter(item => item['key'] !== layerItem['key']);\n this.items.next([...filteredItems, item]);\n this.putItemHook(layerItem);\n return layerItem;\n }\n onExpire(key) {\n return new rxjs_1.Observable(observer => observer.next())\n .pipe(operators_1.timeoutWith(this.config.maxAge, rxjs_1.of(1)), operators_1.skip(1), operators_1.take(1))\n .subscribe(() => this.removeItem(key));\n }\n removeItem(key) {\n const newLayerItems = this.items\n .getValue()\n .filter(item => item['key'] !== key);\n this.map.delete(key);\n this.items.next(newLayerItems);\n }\n getItemObservable(key) {\n return this.items.asObservable().pipe(operators_1.filter(() => !!this.map.has(key)), operators_1.map(() => this.map.get(key)));\n }\n flushCache() {\n return this.items.asObservable().pipe(operators_1.map(items => {\n items.forEach(i => this.removeItem(i['key']));\n return true;\n }));\n }\n}\nexports.CacheLayer = CacheLayer;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction strEnum(o) {\n return o.reduce((res, key) => {\n res[key] = key;\n return res;\n }, Object.create(null));\n}\nexports.InternalEvents = strEnum(['load', 'config']);\nexports.InternalLayers = strEnum(['globalConfig', 'modules']);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass LoggerConfig {\n constructor() {\n this.logging = process.env.LOGGING === 'true' ? true : false;\n this.hashes = true;\n this.date = true;\n this.exitHandler = true;\n this.fileService = true;\n }\n}\nexports.LoggerConfig = LoggerConfig;\nclass PrivateCryptoModel {\n}\nexports.PrivateCryptoModel = PrivateCryptoModel;\nclass ExperimentalFeatures {\n}\nexports.ExperimentalFeatures = ExperimentalFeatures;\nclass InitOptionsConfig {\n}\nexports.InitOptionsConfig = InitOptionsConfig;\nclass ConfigModel {\n constructor() {\n this.init = true;\n this.initOptions = new InitOptionsConfig();\n this.experimental = new ExperimentalFeatures();\n this.logger = new LoggerConfig();\n }\n}\nexports.ConfigModel = ConfigModel;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst config_model_1 = require(\"./config.model\");\nlet ConfigService = class ConfigService {\n constructor() {\n this.config = new config_model_1.ConfigModel();\n }\n setConfig(config) {\n Object.assign(this.config, config);\n }\n};\nConfigService = __decorate([\n Service_1.Service()\n], ConfigService);\nexports.ConfigService = ConfigService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./config.model\"));\n__export(require(\"./config.service\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst container_1 = require(\"../../container\");\nfunction Injector(Service) {\n return function (target, propertyName) {\n Object.defineProperty(target, propertyName, {\n get: () => container_1.Container.get(Service)\n });\n };\n}\nexports.Injector = Injector;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst index_1 = require(\"../config/index\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nlet BootstrapLogger = class BootstrapLogger {\n log(message) {\n if (this.configService.config.logger.logging) {\n const m = [this.logDate(), message];\n console.log(...m);\n return m;\n }\n }\n error(message) {\n console.error(message);\n }\n logImporter(message) {\n if (this.configService.config.logger.logging) {\n return this.log(message);\n }\n }\n logDate() {\n if (this.configService.config.logger.date) {\n return `${Date.now().toPrecision()}`;\n }\n else {\n return '';\n }\n }\n logFileService(message) {\n if (this.configService.config.logger.fileService) {\n this.log(message);\n return '``';\n }\n }\n logHashes(message) {\n if (this.configService.config.logger.hashes) {\n return message;\n }\n else {\n return '';\n }\n }\n logExitHandler(message) {\n if (this.configService.config.logger.exitHandler) {\n this.log(message);\n }\n else {\n return '';\n }\n }\n};\n__decorate([\n injector_decorator_1.Injector(index_1.ConfigService),\n __metadata(\"design:type\", index_1.ConfigService)\n], BootstrapLogger.prototype, \"configService\", void 0);\nBootstrapLogger = __decorate([\n Service_1.Service()\n], BootstrapLogger);\nexports.BootstrapLogger = BootstrapLogger;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./bootstrap-logger\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar CacheService_1;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rxjs_1 = require(\"rxjs\");\nconst operators_1 = require(\"rxjs/operators\");\nconst cache_layer_1 = require(\"./cache-layer\");\nconst events_1 = require(\"../../helpers/events\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst index_1 = require(\"../bootstrap-logger/index\");\nconst FRIENDLY_ERROR_MESSAGES = {\n TRY_TO_UNSUBSCRIBE: 'Someone try to unsubscribe from collection directly... agghhh.. read docs! Blame: '\n};\nlet CacheService = CacheService_1 = class CacheService {\n constructor(logger) {\n this.logger = logger;\n this._cachedLayers = new rxjs_1.BehaviorSubject([]);\n this.map = new Map();\n this.config = {};\n }\n static createCacheInstance(cacheLayer) {\n return new cache_layer_1.CacheLayer(cacheLayer);\n }\n getLayer(name) {\n const exists = this.map.has(name);\n if (!exists) {\n return this.createLayer({ name: name });\n }\n return this.map.get(name);\n }\n getLayersByName(name) {\n return Array.from(this.map.keys())\n .map(item => {\n if (item !== events_1.InternalLayers.modules &&\n item !== events_1.InternalLayers.globalConfig) {\n const config = this.getLayer(item).getItem(events_1.InternalEvents.config);\n if (config && config.data && name === config.data.moduleName) {\n return this.getLayer(config.data.moduleHash);\n }\n }\n })\n .filter(i => !!i);\n }\n searchForDuplicateDependenciesInsideApp() {\n const uniq = [].concat\n .apply([], Array.from(this.map.keys()).map(key => Array.from(this.getLayer(key).map.keys())\n .map(key => (!this.isExcludedEvent(key) ? key : null))\n .filter(i => !!i)))\n .map(name => Object.create({ count: 1, name }))\n .reduce((a, b) => {\n a[b.name] = (a[b.name] || 0) + b.count;\n return a;\n }, {});\n const duplicates = Object.keys(uniq).filter(a => uniq[a] > 1);\n if (duplicates.length) {\n const dups = this.searchForDuplicatesByHash(duplicates[0]);\n const moduleType = dups[0].class['metadata']['type'].charAt(0).toUpperCase() +\n dups[0].class['metadata']['type'].slice(1);\n throw new Error(`\n ${dups[0].class['metadata'].raw}\n ${moduleType}: '${dups[0].originalName}' found multiple times!\n ${moduleType} hash: ${dups[0].moduleHash}\n Modules: [${dups[0].moduleName}, ${dups[1].moduleName}]\n\n Hint: '${dups[0].originalName}' class identity hash is identical in both\n imported files inside ${dups[0].moduleName} and ${dups[1].moduleName}\n consider removing one of the '${dups[0].originalName}'\n `);\n }\n return duplicates;\n }\n isExcludedEvent(i) {\n return i === events_1.InternalEvents.config || i === events_1.InternalEvents.load;\n }\n searchForItem(classItem) {\n return Array.from(this.map.keys())\n .map(module => {\n const currentModule = this.getLayer(module);\n const currentModuleDependencies = Array.from(currentModule.map.keys());\n const found = currentModuleDependencies.filter(i => {\n if (this.isExcludedEvent(i)) {\n return;\n }\n else {\n return i === classItem.name;\n }\n });\n if (found.length) {\n return currentModule.getItem(found[0]).data;\n }\n })\n .filter(i => !!i)[0];\n }\n searchForDuplicatesByHash(key) {\n return Array.from(this.map.keys())\n .map(module => {\n const currentModule = this.getLayer(module);\n const found = Array.from(currentModule.map.keys()).filter(i => {\n if (this.isExcludedEvent(i)) {\n return;\n }\n return i === key;\n });\n if (found.length) {\n const currentFoundItem = currentModule.getItem(found[0]);\n const currentModuleName = this.getLayer(module).getItem(events_1.InternalEvents.config);\n return {\n moduleName: currentModuleName.data.moduleName,\n moduleHash: currentModuleName.data.moduleHash,\n originalName: currentFoundItem.data.originalName,\n dupeName: currentFoundItem.key,\n raw: currentModuleName.data.raw,\n class: currentFoundItem.data\n };\n }\n })\n .filter(i => !!i);\n }\n createLayer(layer) {\n const exists = this.map.has(layer.name);\n if (exists) {\n return this.map.get(layer.name);\n }\n layer.items = layer.items || [];\n layer.config = layer.config || this.config;\n const cacheLayer = CacheService_1.createCacheInstance(layer);\n this.map.set(cacheLayer.name, cacheLayer);\n this._cachedLayers.next([...this._cachedLayers.getValue(), cacheLayer]);\n this.LayerHook(cacheLayer);\n return cacheLayer;\n }\n LayerHook(layerInstance) {\n this.protectLayerFromInvaders(layerInstance);\n if (layerInstance.config.cacheFlushInterval ||\n this.config.cacheFlushInterval) {\n this.OnExpire(layerInstance);\n }\n }\n protectLayerFromInvaders(cacheLayer) {\n cacheLayer.items.constructor.prototype.unsubsribeFromLayer =\n cacheLayer.items.constructor.prototype.unsubscribe;\n cacheLayer.items.constructor.prototype.unsubscribe = () => {\n console.error(FRIENDLY_ERROR_MESSAGES.TRY_TO_UNSUBSCRIBE + cacheLayer.name);\n };\n }\n OnExpire(layerInstance) {\n return new rxjs_1.Observable(observer => observer.next())\n .pipe(operators_1.timeoutWith(layerInstance.config.cacheFlushInterval ||\n this.config.cacheFlushInterval, rxjs_1.of(1)), operators_1.skip(1), operators_1.take(1))\n .subscribe(() => this.removeLayer(layerInstance));\n }\n removeLayer(layerInstance) {\n this.map.delete(layerInstance.name);\n this._cachedLayers.next([\n ...this._cachedLayers\n .getValue()\n .filter(layer => layer.name !== layerInstance.name)\n ]);\n }\n transferItems(name, newCacheLayers) {\n const oldLayer = this.getLayer(name);\n const newLayers = [];\n newCacheLayers.forEach(layerName => {\n const newLayer = this.createLayer(layerName);\n oldLayer.items.getValue().forEach(item => newLayer.putItem(item));\n newLayers.push(newLayer);\n });\n return newLayers;\n }\n flushCache() {\n let oldLayersNames;\n return this._cachedLayers.pipe(operators_1.take(1), operators_1.map((layers) => {\n oldLayersNames = layers.map(l => l.name);\n layers.forEach(layer => this.removeLayer(layer));\n oldLayersNames.forEach(l => this.createLayer({ name: l }));\n return true;\n }));\n }\n};\nCacheService = CacheService_1 = __decorate([\n Service_1.Service(),\n __metadata(\"design:paramtypes\", [index_1.BootstrapLogger])\n], CacheService);\nexports.CacheService = CacheService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass CacheServiceConfigInterface {\n constructor() {\n this.deleteOnExpire = 'aggressive';\n this.cacheFlushInterval = 60 * 60 * 1000;\n this.maxAge = 15 * 60 * 1000;\n this.localStorage = false;\n }\n}\nexports.CacheServiceConfigInterface = CacheServiceConfigInterface;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./cache-layer.service\"));\n__export(require(\"./cache-layer\"));\n__export(require(\"./cache-layer.interfaces\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rxjs_1 = require(\"rxjs\");\n// import { PluginBase, PluginNameVersion, PluginPackage } from 'hapi';\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet PluginService = class PluginService {\n constructor() {\n this.plugins = new rxjs_1.BehaviorSubject([]);\n this.beforePlugins = new rxjs_1.BehaviorSubject([]);\n this.afterPlugins = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.plugins.next([...this.plugins.getValue(), plugin]);\n }\n registerBefore(plugin) {\n this.beforePlugins.next([...this.plugins.getValue(), plugin]);\n }\n registerAfter(plugin) {\n this.afterPlugins.next([...this.plugins.getValue(), plugin]);\n }\n getPlugins() {\n return this.plugins.getValue();\n }\n getAfterPlugins() {\n return this.afterPlugins.getValue();\n }\n getBeforePlugins() {\n return this.beforePlugins.getValue();\n }\n};\nPluginService = __decorate([\n Service_1.Service()\n], PluginService);\nexports.PluginService = PluginService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst rxjs_1 = require(\"rxjs\");\nlet ExitHandlerService = class ExitHandlerService {\n constructor() {\n this.errorHandler = new rxjs_1.Subject();\n }\n init() { }\n exitHandler(options, err) {\n this.errorHandler.next(err);\n if (options.cleanup) {\n this.logger.logExitHandler('AppStopped');\n }\n if (err)\n console.log(err.stack);\n if (options.exit) {\n this.logger.logExitHandler('Unhandled error rejection');\n }\n process.exit(0);\n }\n onExitApp(events) {\n return new rxjs_1.Observable(o => events &&\n events.length &&\n events.forEach(event => process.on(event, e => o.next(e))));\n }\n};\n__decorate([\n injector_decorator_1.Injector(bootstrap_logger_1.BootstrapLogger),\n __metadata(\"design:type\", bootstrap_logger_1.BootstrapLogger)\n], ExitHandlerService.prototype, \"logger\", void 0);\nExitHandlerService = __decorate([\n Service_1.Service()\n], ExitHandlerService);\nexports.ExitHandlerService = ExitHandlerService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./exit-handler.service\"));\n","exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)\n\nexports.writableStream = isFunction(global.WritableStream)\n\nexports.abortController = isFunction(global.AbortController)\n\nexports.blobConstructor = false\ntry {\n\tnew Blob([new ArrayBuffer(1)])\n\texports.blobConstructor = true\n} catch (e) {}\n\n// The xhr request to example.com may violate some restrictive CSP configurations,\n// so if we're running in a browser that supports `fetch`, avoid calling getXHR()\n// and assume support for certain features below.\nvar xhr\nfunction getXHR () {\n\t// Cache the xhr value\n\tif (xhr !== undefined) return xhr\n\n\tif (global.XMLHttpRequest) {\n\t\txhr = new global.XMLHttpRequest()\n\t\t// If XDomainRequest is available (ie only, where xhr might not work\n\t\t// cross domain), use the page location. Otherwise use example.com\n\t\t// Note: this doesn't actually make an http request.\n\t\ttry {\n\t\t\txhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')\n\t\t} catch(e) {\n\t\t\txhr = null\n\t\t}\n\t} else {\n\t\t// Service workers don't have XHR\n\t\txhr = null\n\t}\n\treturn xhr\n}\n\nfunction checkTypeSupport (type) {\n\tvar xhr = getXHR()\n\tif (!xhr) return false\n\ttry {\n\t\txhr.responseType = type\n\t\treturn xhr.responseType === type\n\t} catch (e) {}\n\treturn false\n}\n\n// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.\n// Safari 7.1 appears to have fixed this bug.\nvar haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'\nvar haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)\n\n// If fetch is supported, then arraybuffer will be supported too. Skip calling\n// checkTypeSupport(), since that calls getXHR().\nexports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))\n\n// These next two tests unavoidably show warnings in Chrome. Since fetch will always\n// be used if it's available, just return false for these to avoid the warnings.\nexports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')\nexports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&\n\tcheckTypeSupport('moz-chunked-arraybuffer')\n\n// If fetch is supported, then overrideMimeType will be supported too. Skip calling\n// getXHR().\nexports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)\n\nexports.vbArray = isFunction(global.VBArray)\n\nfunction isFunction (value) {\n\treturn typeof value === 'function'\n}\n\nxhr = null // Help gc\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction $getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return $getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = $getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n ReflectApply(this.listener, this.target, args);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n","module.exports = require('events').EventEmitter;\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(\n uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)\n ))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\n","var capability = require('./capability')\nvar inherits = require('inherits')\nvar stream = require('readable-stream')\n\nvar rStates = exports.readyStates = {\n\tUNSENT: 0,\n\tOPENED: 1,\n\tHEADERS_RECEIVED: 2,\n\tLOADING: 3,\n\tDONE: 4\n}\n\nvar IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {\n\tvar self = this\n\tstream.Readable.call(self)\n\n\tself._mode = mode\n\tself.headers = {}\n\tself.rawHeaders = []\n\tself.trailers = {}\n\tself.rawTrailers = []\n\n\t// Fake the 'close' event, but only once 'end' fires\n\tself.on('end', function () {\n\t\t// The nextTick is necessary to prevent the 'request' module from causing an infinite loop\n\t\tprocess.nextTick(function () {\n\t\t\tself.emit('close')\n\t\t})\n\t})\n\n\tif (mode === 'fetch') {\n\t\tself._fetchResponse = response\n\n\t\tself.url = response.url\n\t\tself.statusCode = response.status\n\t\tself.statusMessage = response.statusText\n\t\t\n\t\tresponse.headers.forEach(function (header, key){\n\t\t\tself.headers[key.toLowerCase()] = header\n\t\t\tself.rawHeaders.push(key, header)\n\t\t})\n\n\t\tif (capability.writableStream) {\n\t\t\tvar writable = new WritableStream({\n\t\t\t\twrite: function (chunk) {\n\t\t\t\t\treturn new Promise(function (resolve, reject) {\n\t\t\t\t\t\tif (self._destroyed) {\n\t\t\t\t\t\t\treject()\n\t\t\t\t\t\t} else if(self.push(new Buffer(chunk))) {\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._resumeFetch = resolve\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t\tclose: function () {\n\t\t\t\t\tglobal.clearTimeout(fetchTimer)\n\t\t\t\t\tif (!self._destroyed)\n\t\t\t\t\t\tself.push(null)\n\t\t\t\t},\n\t\t\t\tabort: function (err) {\n\t\t\t\t\tif (!self._destroyed)\n\t\t\t\t\t\tself.emit('error', err)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\ttry {\n\t\t\t\tresponse.body.pipeTo(writable).catch(function (err) {\n\t\t\t\t\tglobal.clearTimeout(fetchTimer)\n\t\t\t\t\tif (!self._destroyed)\n\t\t\t\t\t\tself.emit('error', err)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t} catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this\n\t\t}\n\t\t// fallback for when writableStream or pipeTo aren't available\n\t\tvar reader = response.body.getReader()\n\t\tfunction read () {\n\t\t\treader.read().then(function (result) {\n\t\t\t\tif (self._destroyed)\n\t\t\t\t\treturn\n\t\t\t\tif (result.done) {\n\t\t\t\t\tglobal.clearTimeout(fetchTimer)\n\t\t\t\t\tself.push(null)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tself.push(new Buffer(result.value))\n\t\t\t\tread()\n\t\t\t}).catch(function (err) {\n\t\t\t\tglobal.clearTimeout(fetchTimer)\n\t\t\t\tif (!self._destroyed)\n\t\t\t\t\tself.emit('error', err)\n\t\t\t})\n\t\t}\n\t\tread()\n\t} else {\n\t\tself._xhr = xhr\n\t\tself._pos = 0\n\n\t\tself.url = xhr.responseURL\n\t\tself.statusCode = xhr.status\n\t\tself.statusMessage = xhr.statusText\n\t\tvar headers = xhr.getAllResponseHeaders().split(/\\r?\\n/)\n\t\theaders.forEach(function (header) {\n\t\t\tvar matches = header.match(/^([^:]+):\\s*(.*)/)\n\t\t\tif (matches) {\n\t\t\t\tvar key = matches[1].toLowerCase()\n\t\t\t\tif (key === 'set-cookie') {\n\t\t\t\t\tif (self.headers[key] === undefined) {\n\t\t\t\t\t\tself.headers[key] = []\n\t\t\t\t\t}\n\t\t\t\t\tself.headers[key].push(matches[2])\n\t\t\t\t} else if (self.headers[key] !== undefined) {\n\t\t\t\t\tself.headers[key] += ', ' + matches[2]\n\t\t\t\t} else {\n\t\t\t\t\tself.headers[key] = matches[2]\n\t\t\t\t}\n\t\t\t\tself.rawHeaders.push(matches[1], matches[2])\n\t\t\t}\n\t\t})\n\n\t\tself._charset = 'x-user-defined'\n\t\tif (!capability.overrideMimeType) {\n\t\t\tvar mimeType = self.rawHeaders['mime-type']\n\t\t\tif (mimeType) {\n\t\t\t\tvar charsetMatch = mimeType.match(/;\\s*charset=([^;])(;|$)/)\n\t\t\t\tif (charsetMatch) {\n\t\t\t\t\tself._charset = charsetMatch[1].toLowerCase()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!self._charset)\n\t\t\t\tself._charset = 'utf-8' // best guess\n\t\t}\n\t}\n}\n\ninherits(IncomingMessage, stream.Readable)\n\nIncomingMessage.prototype._read = function () {\n\tvar self = this\n\n\tvar resolve = self._resumeFetch\n\tif (resolve) {\n\t\tself._resumeFetch = null\n\t\tresolve()\n\t}\n}\n\nIncomingMessage.prototype._onXHRProgress = function () {\n\tvar self = this\n\n\tvar xhr = self._xhr\n\n\tvar response = null\n\tswitch (self._mode) {\n\t\tcase 'text:vbarray': // For IE9\n\t\t\tif (xhr.readyState !== rStates.DONE)\n\t\t\t\tbreak\n\t\t\ttry {\n\t\t\t\t// This fails in IE8\n\t\t\t\tresponse = new global.VBArray(xhr.responseBody).toArray()\n\t\t\t} catch (e) {}\n\t\t\tif (response !== null) {\n\t\t\t\tself.push(new Buffer(response))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Falls through in IE8\t\n\t\tcase 'text':\n\t\t\ttry { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4\n\t\t\t\tresponse = xhr.responseText\n\t\t\t} catch (e) {\n\t\t\t\tself._mode = 'text:vbarray'\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (response.length > self._pos) {\n\t\t\t\tvar newData = response.substr(self._pos)\n\t\t\t\tif (self._charset === 'x-user-defined') {\n\t\t\t\t\tvar buffer = new Buffer(newData.length)\n\t\t\t\t\tfor (var i = 0; i < newData.length; i++)\n\t\t\t\t\t\tbuffer[i] = newData.charCodeAt(i) & 0xff\n\n\t\t\t\t\tself.push(buffer)\n\t\t\t\t} else {\n\t\t\t\t\tself.push(newData, self._charset)\n\t\t\t\t}\n\t\t\t\tself._pos = response.length\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'arraybuffer':\n\t\t\tif (xhr.readyState !== rStates.DONE || !xhr.response)\n\t\t\t\tbreak\n\t\t\tresponse = xhr.response\n\t\t\tself.push(new Buffer(new Uint8Array(response)))\n\t\t\tbreak\n\t\tcase 'moz-chunked-arraybuffer': // take whole\n\t\t\tresponse = xhr.response\n\t\t\tif (xhr.readyState !== rStates.LOADING || !response)\n\t\t\t\tbreak\n\t\t\tself.push(new Buffer(new Uint8Array(response)))\n\t\t\tbreak\n\t\tcase 'ms-stream':\n\t\t\tresponse = xhr.response\n\t\t\tif (xhr.readyState !== rStates.LOADING)\n\t\t\t\tbreak\n\t\t\tvar reader = new global.MSStreamReader()\n\t\t\treader.onprogress = function () {\n\t\t\t\tif (reader.result.byteLength > self._pos) {\n\t\t\t\t\tself.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))\n\t\t\t\t\tself._pos = reader.result.byteLength\n\t\t\t\t}\n\t\t\t}\n\t\t\treader.onload = function () {\n\t\t\t\tself.push(null)\n\t\t\t}\n\t\t\t// reader.onerror = ??? // TODO: this\n\t\t\treader.readAsArrayBuffer(response)\n\t\t\tbreak\n\t}\n\n\t// The ms-stream case handles end separately in reader.onload()\n\tif (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {\n\t\tself.push(null)\n\t}\n}\n","var Buffer = require('buffer').Buffer\n\nmodule.exports = function (buf) {\n\t// If the buffer is backed by a Uint8Array, a faster version will work\n\tif (buf instanceof Uint8Array) {\n\t\t// If the buffer isn't a subarray, return the underlying ArrayBuffer\n\t\tif (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {\n\t\t\treturn buf.buffer\n\t\t} else if (typeof buf.buffer.slice === 'function') {\n\t\t\t// Otherwise we need to get a proper copy\n\t\t\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)\n\t\t}\n\t}\n\n\tif (Buffer.isBuffer(buf)) {\n\t\t// This is the slow version that will work with any Buffer\n\t\t// implementation (even in old browsers)\n\t\tvar arrayCopy = new Uint8Array(buf.length)\n\t\tvar len = buf.length\n\t\tfor (var i = 0; i < len; i++) {\n\t\t\tarrayCopy[i] = buf[i]\n\t\t}\n\t\treturn arrayCopy.buffer\n\t} else {\n\t\tthrow new Error('Argument must be a Buffer')\n\t}\n}\n","var capability = require('./capability')\nvar inherits = require('inherits')\nvar response = require('./response')\nvar stream = require('readable-stream')\nvar toArrayBuffer = require('to-arraybuffer')\n\nvar IncomingMessage = response.IncomingMessage\nvar rStates = response.readyStates\n\nfunction decideMode (preferBinary, useFetch) {\n\tif (capability.fetch && useFetch) {\n\t\treturn 'fetch'\n\t} else if (capability.mozchunkedarraybuffer) {\n\t\treturn 'moz-chunked-arraybuffer'\n\t} else if (capability.msstream) {\n\t\treturn 'ms-stream'\n\t} else if (capability.arraybuffer && preferBinary) {\n\t\treturn 'arraybuffer'\n\t} else if (capability.vbArray && preferBinary) {\n\t\treturn 'text:vbarray'\n\t} else {\n\t\treturn 'text'\n\t}\n}\n\nvar ClientRequest = module.exports = function (opts) {\n\tvar self = this\n\tstream.Writable.call(self)\n\n\tself._opts = opts\n\tself._body = []\n\tself._headers = {}\n\tif (opts.auth)\n\t\tself.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))\n\tObject.keys(opts.headers).forEach(function (name) {\n\t\tself.setHeader(name, opts.headers[name])\n\t})\n\n\tvar preferBinary\n\tvar useFetch = true\n\tif (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {\n\t\t// If the use of XHR should be preferred. Not typically needed.\n\t\tuseFetch = false\n\t\tpreferBinary = true\n\t} else if (opts.mode === 'prefer-streaming') {\n\t\t// If streaming is a high priority but binary compatibility and\n\t\t// the accuracy of the 'content-type' header aren't\n\t\tpreferBinary = false\n\t} else if (opts.mode === 'allow-wrong-content-type') {\n\t\t// If streaming is more important than preserving the 'content-type' header\n\t\tpreferBinary = !capability.overrideMimeType\n\t} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {\n\t\t// Use binary if text streaming may corrupt data or the content-type header, or for speed\n\t\tpreferBinary = true\n\t} else {\n\t\tthrow new Error('Invalid value for opts.mode')\n\t}\n\tself._mode = decideMode(preferBinary, useFetch)\n\tself._fetchTimer = null\n\n\tself.on('finish', function () {\n\t\tself._onFinish()\n\t})\n}\n\ninherits(ClientRequest, stream.Writable)\n\nClientRequest.prototype.setHeader = function (name, value) {\n\tvar self = this\n\tvar lowerName = name.toLowerCase()\n\t// This check is not necessary, but it prevents warnings from browsers about setting unsafe\n\t// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but\n\t// http-browserify did it, so I will too.\n\tif (unsafeHeaders.indexOf(lowerName) !== -1)\n\t\treturn\n\n\tself._headers[lowerName] = {\n\t\tname: name,\n\t\tvalue: value\n\t}\n}\n\nClientRequest.prototype.getHeader = function (name) {\n\tvar header = this._headers[name.toLowerCase()]\n\tif (header)\n\t\treturn header.value\n\treturn null\n}\n\nClientRequest.prototype.removeHeader = function (name) {\n\tvar self = this\n\tdelete self._headers[name.toLowerCase()]\n}\n\nClientRequest.prototype._onFinish = function () {\n\tvar self = this\n\n\tif (self._destroyed)\n\t\treturn\n\tvar opts = self._opts\n\n\tvar headersObj = self._headers\n\tvar body = null\n\tif (opts.method !== 'GET' && opts.method !== 'HEAD') {\n\t\tif (capability.arraybuffer) {\n\t\t\tbody = toArrayBuffer(Buffer.concat(self._body))\n\t\t} else if (capability.blobConstructor) {\n\t\t\tbody = new global.Blob(self._body.map(function (buffer) {\n\t\t\t\treturn toArrayBuffer(buffer)\n\t\t\t}), {\n\t\t\t\ttype: (headersObj['content-type'] || {}).value || ''\n\t\t\t})\n\t\t} else {\n\t\t\t// get utf8 string\n\t\t\tbody = Buffer.concat(self._body).toString()\n\t\t}\n\t}\n\n\t// create flattened list of headers\n\tvar headersList = []\n\tObject.keys(headersObj).forEach(function (keyName) {\n\t\tvar name = headersObj[keyName].name\n\t\tvar value = headersObj[keyName].value\n\t\tif (Array.isArray(value)) {\n\t\t\tvalue.forEach(function (v) {\n\t\t\t\theadersList.push([name, v])\n\t\t\t})\n\t\t} else {\n\t\t\theadersList.push([name, value])\n\t\t}\n\t})\n\n\tif (self._mode === 'fetch') {\n\t\tvar signal = null\n\t\tvar fetchTimer = null\n\t\tif (capability.abortController) {\n\t\t\tvar controller = new AbortController()\n\t\t\tsignal = controller.signal\n\t\t\tself._fetchAbortController = controller\n\n\t\t\tif ('requestTimeout' in opts && opts.requestTimeout !== 0) {\n\t\t\t\tself._fetchTimer = global.setTimeout(function () {\n\t\t\t\t\tself.emit('requestTimeout')\n\t\t\t\t\tif (self._fetchAbortController)\n\t\t\t\t\t\tself._fetchAbortController.abort()\n\t\t\t\t}, opts.requestTimeout)\n\t\t\t}\n\t\t}\n\n\t\tglobal.fetch(self._opts.url, {\n\t\t\tmethod: self._opts.method,\n\t\t\theaders: headersList,\n\t\t\tbody: body || undefined,\n\t\t\tmode: 'cors',\n\t\t\tcredentials: opts.withCredentials ? 'include' : 'same-origin',\n\t\t\tsignal: signal\n\t\t}).then(function (response) {\n\t\t\tself._fetchResponse = response\n\t\t\tself._connect()\n\t\t}, function (reason) {\n\t\t\tglobal.clearTimeout(self._fetchTimer)\n\t\t\tif (!self._destroyed)\n\t\t\t\tself.emit('error', reason)\n\t\t})\n\t} else {\n\t\tvar xhr = self._xhr = new global.XMLHttpRequest()\n\t\ttry {\n\t\t\txhr.open(self._opts.method, self._opts.url, true)\n\t\t} catch (err) {\n\t\t\tprocess.nextTick(function () {\n\t\t\t\tself.emit('error', err)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Can't set responseType on really old browsers\n\t\tif ('responseType' in xhr)\n\t\t\txhr.responseType = self._mode.split(':')[0]\n\n\t\tif ('withCredentials' in xhr)\n\t\t\txhr.withCredentials = !!opts.withCredentials\n\n\t\tif (self._mode === 'text' && 'overrideMimeType' in xhr)\n\t\t\txhr.overrideMimeType('text/plain; charset=x-user-defined')\n\n\t\tif ('requestTimeout' in opts) {\n\t\t\txhr.timeout = opts.requestTimeout\n\t\t\txhr.ontimeout = function () {\n\t\t\t\tself.emit('requestTimeout')\n\t\t\t}\n\t\t}\n\n\t\theadersList.forEach(function (header) {\n\t\t\txhr.setRequestHeader(header[0], header[1])\n\t\t})\n\n\t\tself._response = null\n\t\txhr.onreadystatechange = function () {\n\t\t\tswitch (xhr.readyState) {\n\t\t\t\tcase rStates.LOADING:\n\t\t\t\tcase rStates.DONE:\n\t\t\t\t\tself._onXHRProgress()\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Necessary for streaming in Firefox, since xhr.response is ONLY defined\n\t\t// in onprogress, not in onreadystatechange with xhr.readyState = 3\n\t\tif (self._mode === 'moz-chunked-arraybuffer') {\n\t\t\txhr.onprogress = function () {\n\t\t\t\tself._onXHRProgress()\n\t\t\t}\n\t\t}\n\n\t\txhr.onerror = function () {\n\t\t\tif (self._destroyed)\n\t\t\t\treturn\n\t\t\tself.emit('error', new Error('XHR error'))\n\t\t}\n\n\t\ttry {\n\t\t\txhr.send(body)\n\t\t} catch (err) {\n\t\t\tprocess.nextTick(function () {\n\t\t\t\tself.emit('error', err)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n}\n\n/**\n * Checks if xhr.status is readable and non-zero, indicating no error.\n * Even though the spec says it should be available in readyState 3,\n * accessing it throws an exception in IE8\n */\nfunction statusValid (xhr) {\n\ttry {\n\t\tvar status = xhr.status\n\t\treturn (status !== null && status !== 0)\n\t} catch (e) {\n\t\treturn false\n\t}\n}\n\nClientRequest.prototype._onXHRProgress = function () {\n\tvar self = this\n\n\tif (!statusValid(self._xhr) || self._destroyed)\n\t\treturn\n\n\tif (!self._response)\n\t\tself._connect()\n\n\tself._response._onXHRProgress()\n}\n\nClientRequest.prototype._connect = function () {\n\tvar self = this\n\n\tif (self._destroyed)\n\t\treturn\n\n\tself._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)\n\tself._response.on('error', function(err) {\n\t\tself.emit('error', err)\n\t})\n\n\tself.emit('response', self._response)\n}\n\nClientRequest.prototype._write = function (chunk, encoding, cb) {\n\tvar self = this\n\n\tself._body.push(chunk)\n\tcb()\n}\n\nClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {\n\tvar self = this\n\tself._destroyed = true\n\tglobal.clearTimeout(self._fetchTimer)\n\tif (self._response)\n\t\tself._response._destroyed = true\n\tif (self._xhr)\n\t\tself._xhr.abort()\n\telse if (self._fetchAbortController)\n\t\tself._fetchAbortController.abort()\n}\n\nClientRequest.prototype.end = function (data, encoding, cb) {\n\tvar self = this\n\tif (typeof data === 'function') {\n\t\tcb = data\n\t\tdata = undefined\n\t}\n\n\tstream.Writable.prototype.end.call(self, data, encoding, cb)\n}\n\nClientRequest.prototype.flushHeaders = function () {}\nClientRequest.prototype.setTimeout = function () {}\nClientRequest.prototype.setNoDelay = function () {}\nClientRequest.prototype.setSocketKeepAlive = function () {}\n\n// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method\nvar unsafeHeaders = [\n\t'accept-charset',\n\t'accept-encoding',\n\t'access-control-request-headers',\n\t'access-control-request-method',\n\t'connection',\n\t'content-length',\n\t'cookie',\n\t'cookie2',\n\t'date',\n\t'dnt',\n\t'expect',\n\t'host',\n\t'keep-alive',\n\t'origin',\n\t'referer',\n\t'te',\n\t'trailer',\n\t'transfer-encoding',\n\t'upgrade',\n\t'via'\n]\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","module.exports = {\n \"100\": \"Continue\",\n \"101\": \"Switching Protocols\",\n \"102\": \"Processing\",\n \"200\": \"OK\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"203\": \"Non-Authoritative Information\",\n \"204\": \"No Content\",\n \"205\": \"Reset Content\",\n \"206\": \"Partial Content\",\n \"207\": \"Multi-Status\",\n \"208\": \"Already Reported\",\n \"226\": \"IM Used\",\n \"300\": \"Multiple Choices\",\n \"301\": \"Moved Permanently\",\n \"302\": \"Found\",\n \"303\": \"See Other\",\n \"304\": \"Not Modified\",\n \"305\": \"Use Proxy\",\n \"307\": \"Temporary Redirect\",\n \"308\": \"Permanent Redirect\",\n \"400\": \"Bad Request\",\n \"401\": \"Unauthorized\",\n \"402\": \"Payment Required\",\n \"403\": \"Forbidden\",\n \"404\": \"Not Found\",\n \"405\": \"Method Not Allowed\",\n \"406\": \"Not Acceptable\",\n \"407\": \"Proxy Authentication Required\",\n \"408\": \"Request Timeout\",\n \"409\": \"Conflict\",\n \"410\": \"Gone\",\n \"411\": \"Length Required\",\n \"412\": \"Precondition Failed\",\n \"413\": \"Payload Too Large\",\n \"414\": \"URI Too Long\",\n \"415\": \"Unsupported Media Type\",\n \"416\": \"Range Not Satisfiable\",\n \"417\": \"Expectation Failed\",\n \"418\": \"I'm a teapot\",\n \"421\": \"Misdirected Request\",\n \"422\": \"Unprocessable Entity\",\n \"423\": \"Locked\",\n \"424\": \"Failed Dependency\",\n \"425\": \"Unordered Collection\",\n \"426\": \"Upgrade Required\",\n \"428\": \"Precondition Required\",\n \"429\": \"Too Many Requests\",\n \"431\": \"Request Header Fields Too Large\",\n \"451\": \"Unavailable For Legal Reasons\",\n \"500\": \"Internal Server Error\",\n \"501\": \"Not Implemented\",\n \"502\": \"Bad Gateway\",\n \"503\": \"Service Unavailable\",\n \"504\": \"Gateway Timeout\",\n \"505\": \"HTTP Version Not Supported\",\n \"506\": \"Variant Also Negotiates\",\n \"507\": \"Insufficient Storage\",\n \"508\": \"Loop Detected\",\n \"509\": \"Bandwidth Limit Exceeded\",\n \"510\": \"Not Extended\",\n \"511\": \"Network Authentication Required\"\n}\n","/*! https://mths.be/punycode v1.4.1 by @mathias */\n;(function(root) {\n\n\t/** Detect free variables */\n\tvar freeExports = typeof exports == 'object' && exports &&\n\t\t!exports.nodeType && exports;\n\tvar freeModule = typeof module == 'object' && module &&\n\t\t!module.nodeType && module;\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (\n\t\tfreeGlobal.global === freeGlobal ||\n\t\tfreeGlobal.window === freeGlobal ||\n\t\tfreeGlobal.self === freeGlobal\n\t) {\n\t\troot = freeGlobal;\n\t}\n\n\t/**\n\t * The `punycode` object.\n\t * @name punycode\n\t * @type Object\n\t */\n\tvar punycode,\n\n\t/** Highest positive signed 32-bit float value */\n\tmaxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1\n\n\t/** Bootstring parameters */\n\tbase = 36,\n\ttMin = 1,\n\ttMax = 26,\n\tskew = 38,\n\tdamp = 700,\n\tinitialBias = 72,\n\tinitialN = 128, // 0x80\n\tdelimiter = '-', // '\\x2D'\n\n\t/** Regular expressions */\n\tregexPunycode = /^xn--/,\n\tregexNonASCII = /[^\\x20-\\x7E]/, // unprintable ASCII chars + non-ASCII chars\n\tregexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g, // RFC 3490 separators\n\n\t/** Error messages */\n\terrors = {\n\t\t'overflow': 'Overflow: input needs wider integers to process',\n\t\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t\t'invalid-input': 'Invalid input'\n\t},\n\n\t/** Convenience shortcuts */\n\tbaseMinusTMin = base - tMin,\n\tfloor = Math.floor,\n\tstringFromCharCode = String.fromCharCode,\n\n\t/** Temporary variable */\n\tkey;\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/**\n\t * A generic error utility function.\n\t * @private\n\t * @param {String} type The error type.\n\t * @returns {Error} Throws a `RangeError` with the applicable error message.\n\t */\n\tfunction error(type) {\n\t\tthrow new RangeError(errors[type]);\n\t}\n\n\t/**\n\t * A generic `Array#map` utility function.\n\t * @private\n\t * @param {Array} array The array to iterate over.\n\t * @param {Function} callback The function that gets called for every array\n\t * item.\n\t * @returns {Array} A new array of values returned by the callback function.\n\t */\n\tfunction map(array, fn) {\n\t\tvar length = array.length;\n\t\tvar result = [];\n\t\twhile (length--) {\n\t\t\tresult[length] = fn(array[length]);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * A simple `Array#map`-like wrapper to work with domain name strings or email\n\t * addresses.\n\t * @private\n\t * @param {String} domain The domain name or email address.\n\t * @param {Function} callback The function that gets called for every\n\t * character.\n\t * @returns {Array} A new string of characters returned by the callback\n\t * function.\n\t */\n\tfunction mapDomain(string, fn) {\n\t\tvar parts = string.split('@');\n\t\tvar result = '';\n\t\tif (parts.length > 1) {\n\t\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t\t// the local part (i.e. everything up to `@`) intact.\n\t\t\tresult = parts[0] + '@';\n\t\t\tstring = parts[1];\n\t\t}\n\t\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\t\tstring = string.replace(regexSeparators, '\\x2E');\n\t\tvar labels = string.split('.');\n\t\tvar encoded = map(labels, fn).join('.');\n\t\treturn result + encoded;\n\t}\n\n\t/**\n\t * Creates an array containing the numeric code points of each Unicode\n\t * character in the string. While JavaScript uses UCS-2 internally,\n\t * this function will convert a pair of surrogate halves (each of which\n\t * UCS-2 exposes as separate characters) into a single code point,\n\t * matching UTF-16.\n\t * @see `punycode.ucs2.encode`\n\t * @see \n\t * @memberOf punycode.ucs2\n\t * @name decode\n\t * @param {String} string The Unicode input string (UCS-2).\n\t * @returns {Array} The new array of code points.\n\t */\n\tfunction ucs2decode(string) {\n\t\tvar output = [],\n\t\t counter = 0,\n\t\t length = string.length,\n\t\t value,\n\t\t extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t/**\n\t * Creates a string based on an array of numeric code points.\n\t * @see `punycode.ucs2.decode`\n\t * @memberOf punycode.ucs2\n\t * @name encode\n\t * @param {Array} codePoints The array of numeric code points.\n\t * @returns {String} The new Unicode string (UCS-2).\n\t */\n\tfunction ucs2encode(array) {\n\t\treturn map(array, function(value) {\n\t\t\tvar output = '';\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t\treturn output;\n\t\t}).join('');\n\t}\n\n\t/**\n\t * Converts a basic code point into a digit/integer.\n\t * @see `digitToBasic()`\n\t * @private\n\t * @param {Number} codePoint The basic numeric code point value.\n\t * @returns {Number} The numeric value of a basic code point (for use in\n\t * representing integers) in the range `0` to `base - 1`, or `base` if\n\t * the code point does not represent a value.\n\t */\n\tfunction basicToDigit(codePoint) {\n\t\tif (codePoint - 48 < 10) {\n\t\t\treturn codePoint - 22;\n\t\t}\n\t\tif (codePoint - 65 < 26) {\n\t\t\treturn codePoint - 65;\n\t\t}\n\t\tif (codePoint - 97 < 26) {\n\t\t\treturn codePoint - 97;\n\t\t}\n\t\treturn base;\n\t}\n\n\t/**\n\t * Converts a digit/integer into a basic code point.\n\t * @see `basicToDigit()`\n\t * @private\n\t * @param {Number} digit The numeric value of a basic code point.\n\t * @returns {Number} The basic code point whose value (when used for\n\t * representing integers) is `digit`, which needs to be in the range\n\t * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n\t * used; else, the lowercase form is used. The behavior is undefined\n\t * if `flag` is non-zero and `digit` has no uppercase form.\n\t */\n\tfunction digitToBasic(digit, flag) {\n\t\t// 0..25 map to ASCII a..z or A..Z\n\t\t// 26..35 map to ASCII 0..9\n\t\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n\t}\n\n\t/**\n\t * Bias adaptation function as per section 3.4 of RFC 3492.\n\t * https://tools.ietf.org/html/rfc3492#section-3.4\n\t * @private\n\t */\n\tfunction adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}\n\n\t/**\n\t * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n\t * symbols.\n\t * @memberOf punycode\n\t * @param {String} input The Punycode string of ASCII-only symbols.\n\t * @returns {String} The resulting string of Unicode symbols.\n\t */\n\tfunction decode(input) {\n\t\t// Don't use UCS-2\n\t\tvar output = [],\n\t\t inputLength = input.length,\n\t\t out,\n\t\t i = 0,\n\t\t n = initialN,\n\t\t bias = initialBias,\n\t\t basic,\n\t\t j,\n\t\t index,\n\t\t oldi,\n\t\t w,\n\t\t k,\n\t\t digit,\n\t\t t,\n\t\t /** Cached calculation results */\n\t\t baseMinusT;\n\n\t\t// Handle the basic code points: let `basic` be the number of input code\n\t\t// points before the last delimiter, or `0` if there is none, then copy\n\t\t// the first basic code points to the output.\n\n\t\tbasic = input.lastIndexOf(delimiter);\n\t\tif (basic < 0) {\n\t\t\tbasic = 0;\n\t\t}\n\n\t\tfor (j = 0; j < basic; ++j) {\n\t\t\t// if it's not a basic code point\n\t\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\t\terror('not-basic');\n\t\t\t}\n\t\t\toutput.push(input.charCodeAt(j));\n\t\t}\n\n\t\t// Main decoding loop: start just after the last delimiter if any basic code\n\t\t// points were copied; start at the beginning otherwise.\n\n\t\tfor (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t\t// `index` is the index of the next character to be consumed.\n\t\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t\t// which gets added to `i`. The overflow checking is easier\n\t\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t\t// value at the end to obtain `delta`.\n\t\t\tfor (oldi = i, w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\t\tif (index >= inputLength) {\n\t\t\t\t\terror('invalid-input');\n\t\t\t\t}\n\n\t\t\t\tdigit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\ti += digit * w;\n\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\t\tif (digit < t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbaseMinusT = base - t;\n\t\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tw *= baseMinusT;\n\n\t\t\t}\n\n\t\t\tout = output.length + 1;\n\t\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t\t// incrementing `n` each time, so we'll fix that now:\n\t\t\tif (floor(i / out) > maxInt - n) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tn += floor(i / out);\n\t\t\ti %= out;\n\n\t\t\t// Insert `n` at position `i` of the output\n\t\t\toutput.splice(i++, 0, n);\n\n\t\t}\n\n\t\treturn ucs2encode(output);\n\t}\n\n\t/**\n\t * Converts a string of Unicode symbols (e.g. a domain name label) to a\n\t * Punycode string of ASCII-only symbols.\n\t * @memberOf punycode\n\t * @param {String} input The string of Unicode symbols.\n\t * @returns {String} The resulting Punycode string of ASCII-only symbols.\n\t */\n\tfunction encode(input) {\n\t\tvar n,\n\t\t delta,\n\t\t handledCPCount,\n\t\t basicLength,\n\t\t bias,\n\t\t j,\n\t\t m,\n\t\t q,\n\t\t k,\n\t\t t,\n\t\t currentValue,\n\t\t output = [],\n\t\t /** `inputLength` will hold the number of code points in `input`. */\n\t\t inputLength,\n\t\t /** Cached calculation results */\n\t\t handledCPCountPlusOne,\n\t\t baseMinusT,\n\t\t qMinusT;\n\n\t\t// Convert the input in UCS-2 to Unicode\n\t\tinput = ucs2decode(input);\n\n\t\t// Cache the length\n\t\tinputLength = input.length;\n\n\t\t// Initialize the state\n\t\tn = initialN;\n\t\tdelta = 0;\n\t\tbias = initialBias;\n\n\t\t// Handle the basic code points\n\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\tcurrentValue = input[j];\n\t\t\tif (currentValue < 0x80) {\n\t\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t\t}\n\t\t}\n\n\t\thandledCPCount = basicLength = output.length;\n\n\t\t// `handledCPCount` is the number of code points that have been handled;\n\t\t// `basicLength` is the number of basic code points.\n\n\t\t// Finish the basic string - if it is not empty - with a delimiter\n\t\tif (basicLength) {\n\t\t\toutput.push(delimiter);\n\t\t}\n\n\t\t// Main encoding loop:\n\t\twhile (handledCPCount < inputLength) {\n\n\t\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t\t// larger one:\n\t\t\tfor (m = maxInt, j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\t\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\t\tm = currentValue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t\t// but guard against overflow\n\t\t\thandledCPCountPlusOne = handledCPCount + 1;\n\t\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\t\tn = m;\n\n\t\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\n\t\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tif (currentValue == n) {\n\t\t\t\t\t// Represent delta as a generalized variable-length integer\n\t\t\t\t\tfor (q = delta, k = base; /* no condition */; k += base) {\n\t\t\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqMinusT = q - t;\n\t\t\t\t\t\tbaseMinusT = base - t;\n\t\t\t\t\t\toutput.push(\n\t\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t\t);\n\t\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\t\tdelta = 0;\n\t\t\t\t\t++handledCPCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t++delta;\n\t\t\t++n;\n\n\t\t}\n\t\treturn output.join('');\n\t}\n\n\t/**\n\t * Converts a Punycode string representing a domain name or an email address\n\t * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n\t * it doesn't matter if you call it on a string that has already been\n\t * converted to Unicode.\n\t * @memberOf punycode\n\t * @param {String} input The Punycoded domain name or email address to\n\t * convert to Unicode.\n\t * @returns {String} The Unicode representation of the given Punycode\n\t * string.\n\t */\n\tfunction toUnicode(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexPunycode.test(string)\n\t\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/**\n\t * Converts a Unicode string representing a domain name or an email address to\n\t * Punycode. Only the non-ASCII parts of the domain name will be converted,\n\t * i.e. it doesn't matter if you call it with a domain that's already in\n\t * ASCII.\n\t * @memberOf punycode\n\t * @param {String} input The domain name or email address to convert, as a\n\t * Unicode string.\n\t * @returns {String} The Punycode representation of the given domain name or\n\t * email address.\n\t */\n\tfunction toASCII(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexNonASCII.test(string)\n\t\t\t\t? 'xn--' + encode(string)\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/** Define the public API */\n\tpunycode = {\n\t\t/**\n\t\t * A string representing the current Punycode.js version number.\n\t\t * @memberOf punycode\n\t\t * @type String\n\t\t */\n\t\t'version': '1.4.1',\n\t\t/**\n\t\t * An object of methods to convert from JavaScript's internal character\n\t\t * representation (UCS-2) to Unicode code points, and back.\n\t\t * @see \n\t\t * @memberOf punycode\n\t\t * @type Object\n\t\t */\n\t\t'ucs2': {\n\t\t\t'decode': ucs2decode,\n\t\t\t'encode': ucs2encode\n\t\t},\n\t\t'decode': decode,\n\t\t'encode': encode,\n\t\t'toASCII': toASCII,\n\t\t'toUnicode': toUnicode\n\t};\n\n\t/** Expose `punycode` */\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine('punycode', function() {\n\t\t\treturn punycode;\n\t\t});\n\t} else if (freeExports && freeModule) {\n\t\tif (module.exports == freeExports) {\n\t\t\t// in Node.js, io.js, or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = punycode;\n\t\t} else {\n\t\t\t// in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (key in punycode) {\n\t\t\t\tpunycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// in Rhino or a web browser\n\t\troot.punycode = punycode;\n\t}\n\n}(this));\n","'use strict';\n\nmodule.exports = {\n isString: function(arg) {\n return typeof(arg) === 'string';\n },\n isObject: function(arg) {\n return typeof(arg) === 'object' && arg !== null;\n },\n isNull: function(arg) {\n return arg === null;\n },\n isNullOrUndefined: function(arg) {\n return arg == null;\n }\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return map(objectKeys(obj), function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (isArray(obj[k])) {\n return map(obj[k], function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f(xs[i], i));\n }\n return res;\n}\n\nvar objectKeys = Object.keys || function (obj) {\n var res = [];\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);\n }\n return res;\n};\n","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n","var ClientRequest = require('./lib/request')\nvar response = require('./lib/response')\nvar extend = require('xtend')\nvar statusCodes = require('builtin-status-codes')\nvar url = require('url')\n\nvar http = exports\n\nhttp.request = function (opts, cb) {\n\tif (typeof opts === 'string')\n\t\topts = url.parse(opts)\n\telse\n\t\topts = extend(opts)\n\n\t// Normally, the page is loaded from http or https, so not specifying a protocol\n\t// will result in a (valid) protocol-relative url. However, this won't work if\n\t// the protocol is something else, like 'file:'\n\tvar defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''\n\n\tvar protocol = opts.protocol || defaultProtocol\n\tvar host = opts.hostname || opts.host\n\tvar port = opts.port\n\tvar path = opts.path || '/'\n\n\t// Necessary for IPv6 addresses\n\tif (host && host.indexOf(':') !== -1)\n\t\thost = '[' + host + ']'\n\n\t// This may be a relative url. The browser should always be able to interpret it correctly.\n\topts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path\n\topts.method = (opts.method || 'GET').toUpperCase()\n\topts.headers = opts.headers || {}\n\n\t// Also valid opts.auth, opts.mode\n\n\tvar req = new ClientRequest(opts)\n\tif (cb)\n\t\treq.on('response', cb)\n\treturn req\n}\n\nhttp.get = function get (opts, cb) {\n\tvar req = http.request(opts, cb)\n\treq.end()\n\treturn req\n}\n\nhttp.ClientRequest = ClientRequest\nhttp.IncomingMessage = response.IncomingMessage\n\nhttp.Agent = function () {}\nhttp.Agent.defaultMaxSockets = 4\n\nhttp.globalAgent = new http.Agent()\n\nhttp.STATUS_CODES = statusCodes\n\nhttp.METHODS = [\n\t'CHECKOUT',\n\t'CONNECT',\n\t'COPY',\n\t'DELETE',\n\t'GET',\n\t'HEAD',\n\t'LOCK',\n\t'M-SEARCH',\n\t'MERGE',\n\t'MKACTIVITY',\n\t'MKCOL',\n\t'MOVE',\n\t'NOTIFY',\n\t'OPTIONS',\n\t'PATCH',\n\t'POST',\n\t'PROPFIND',\n\t'PROPPATCH',\n\t'PURGE',\n\t'PUT',\n\t'REPORT',\n\t'SEARCH',\n\t'SUBSCRIBE',\n\t'TRACE',\n\t'UNLOCK',\n\t'UNSUBSCRIBE'\n]","var http = require('http')\nvar url = require('url')\n\nvar https = module.exports\n\nfor (var key in http) {\n if (http.hasOwnProperty(key)) https[key] = http[key]\n}\n\nhttps.request = function (params, cb) {\n params = validateParams(params)\n return http.request.call(this, params, cb)\n}\n\nhttps.get = function (params, cb) {\n params = validateParams(params)\n return http.get.call(this, params, cb)\n}\n\nfunction validateParams (params) {\n if (typeof params === 'string') {\n params = url.parse(params)\n }\n if (!params.protocol) {\n params.protocol = 'https:'\n }\n if (params.protocol !== 'https:') {\n throw new Error('Protocol \"' + params.protocol + '\" not supported. Expected \"https:\"')\n }\n return params\n}\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst index_1 = require(\"../cache/index\");\nconst container_1 = require(\"../../container\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet RequestCacheService = class RequestCacheService extends index_1.CacheService {\n constructor() {\n super(container_1.Container.get(bootstrap_logger_1.BootstrapLogger));\n this.cacheLayer = this.createLayer({ name: 'request-cache-layer' });\n }\n put(key, data) {\n return this.cacheLayer.putItem({ key, data });\n }\n get(key) {\n return this.cacheLayer.getItem(key);\n }\n};\nRequestCacheService = __decorate([\n Service_1.Service(),\n __metadata(\"design:paramtypes\", [])\n], RequestCacheService);\nexports.RequestCacheService = RequestCacheService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nconst http_1 = require(\"http\");\nconst https_1 = require(\"https\");\nconst request_cache_service_1 = require(\"./request.cache.service\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst operators_1 = require(\"rxjs/operators\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger\");\nlet RequestService = class RequestService {\n get(link, cacheHash) {\n if (this.cache.cacheLayer.map.has(link)) {\n this.logger.log(`Item returned from cacahe: ${link}`);\n return rxjs_1.of(this.cache.cacheLayer.get(link).data);\n }\n return new rxjs_1.Observable(o => {\n if (link.includes('https://')) {\n https_1.get(link, resp => {\n let data = '';\n resp.on('data', chunk => (data += chunk));\n resp.on('end', () => o.next(data));\n }).on('error', err => {\n console.error('Error: ' + err.message);\n o.error(err);\n });\n }\n else {\n http_1.get(link, resp => {\n let data = '';\n resp.on('data', chunk => (data += chunk));\n resp.on('end', () => o.next(data));\n }).on('error', err => {\n console.error('Error: ' + err.message);\n o.error(err);\n });\n }\n }).pipe(operators_1.tap(res => this.cache.cacheLayer.putItem({ key: link, data: res })));\n }\n};\n__decorate([\n injector_decorator_1.Injector(request_cache_service_1.RequestCacheService),\n __metadata(\"design:type\", request_cache_service_1.RequestCacheService)\n], RequestService.prototype, \"cache\", void 0);\n__decorate([\n injector_decorator_1.Injector(bootstrap_logger_1.BootstrapLogger),\n __metadata(\"design:type\", bootstrap_logger_1.BootstrapLogger)\n], RequestService.prototype, \"logger\", void 0);\nRequestService = __decorate([\n Service_1.Service()\n], RequestService);\nexports.RequestService = RequestService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./request.service\"));\n__export(require(\"./request.cache.service\"));\n","// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,\n// backported and transplited with Babel, with backwards-compat fixes\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// path.resolve([from ...], to)\n// posix version\nexports.resolve = function() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : process.cwd();\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexports.normalize = function(path) {\n var isAbsolute = exports.isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isAbsolute).join('/');\n\n if (!path && !isAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexports.isAbsolute = function(path) {\n return path.charAt(0) === '/';\n};\n\n// posix version\nexports.join = function() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return exports.normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n};\n\n\n// path.relative(from, to)\n// posix version\nexports.relative = function(from, to) {\n from = exports.resolve(from).substr(1);\n to = exports.resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n};\n\nexports.sep = '/';\nexports.delimiter = ':';\n\nexports.dirname = function (path) {\n if (typeof path !== 'string') path = path + '';\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) {\n // return '//';\n // Backwards-compat fix:\n return '/';\n }\n return path.slice(0, end);\n};\n\nfunction basename(path) {\n if (typeof path !== 'string') path = path + '';\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n}\n\n// Uses a mixed approach for backwards-compatibility, as ext behavior changed\n// in new Node.js versions, so only basename() above is backported here\nexports.basename = function (path, ext) {\n var f = basename(path);\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n};\n\nexports.extname = function (path) {\n if (typeof path !== 'string') path = path + '';\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n};\n\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b'\n ? function (str, start, len) { return str.substr(start, len) }\n : function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst path = require('path');\nconst fs = require('fs');\nconst _0777 = parseInt('0777', 8);\nfunction mkdirp(p, opts, f, made) {\n if (typeof opts === 'function') {\n f = opts;\n opts = {};\n }\n else if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n let mode = opts.mode;\n const xfs = opts.fs || fs;\n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made)\n made = null;\n const cb = f || function () { };\n p = path.resolve(p);\n xfs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirp(path.dirname(p), opts, function (er, made) {\n if (er)\n cb(er, made);\n else\n mkdirp(p, opts, cb, made);\n });\n break;\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n xfs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory())\n cb(er, made);\n else\n cb(null, made);\n });\n break;\n }\n });\n}\nexports.mkdirp = mkdirp;\nfunction mkdirpSync(p, opts, made) {\n if (!opts || typeof opts !== 'object') {\n opts = { mode: opts };\n }\n let mode = opts.mode;\n const xfs = opts.fs || fs;\n if (mode === undefined) {\n mode = _0777 & (~process.umask());\n }\n if (!made)\n made = null;\n p = path.resolve(p);\n try {\n xfs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT':\n made = mkdirpSync(path.dirname(p), opts, made);\n mkdirpSync(p, opts, made);\n break;\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n let stat;\n try {\n stat = xfs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory())\n throw err0;\n break;\n }\n }\n return made;\n}\nexports.mkdirpSync = mkdirpSync;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst fs_1 = require(\"fs\");\nconst rxjs_1 = require(\"rxjs\");\nconst operators_1 = require(\"rxjs/operators\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst path_1 = require(\"path\");\nconst dist_1 = require(\"./dist\");\nlet FileService = class FileService {\n writeFile(folder, fileName, moduleName, file) {\n return this.mkdirp(folder).pipe(operators_1.tap(() => {\n this.logger.logFileService(`Bootstrap: @Service('${moduleName}'): Saved inside ${folder}`);\n }), operators_1.switchMap(() => this.writeFileAsyncP(folder, fileName, file)));\n }\n writeFileAsync(folder, fileName, moduleName, file) {\n return this.mkdirp(folder).pipe(operators_1.switchMap(() => this.writeFileAsyncP(folder, fileName, file)), operators_1.map(() => {\n this.logger.logFileService(`Bootstrap: external @Module('${moduleName}') namespace: Saved inside ${folder}`);\n return `${folder}/${fileName}`;\n }));\n }\n writeFileSync(folder, file) {\n return fs_1.writeFileSync.bind(null)(folder, JSON.stringify(file, null, 2) + '\\n', { encoding: 'utf-8' });\n }\n readFile(file) {\n return JSON.parse(fs_1.readFileSync.bind(null)(file, { encoding: 'utf-8' }));\n }\n isPresent(path) {\n return fs_1.existsSync(path);\n }\n writeFileAsyncP(folder, fileName, content) {\n return new rxjs_1.Observable(o => fs_1.writeFile(`${folder}/${fileName}`, content, () => o.next(true)));\n }\n mkdirp(folder) {\n return new rxjs_1.Observable(observer => {\n dist_1.mkdirp(folder, err => {\n if (err) {\n console.error(err);\n observer.error(false);\n }\n else {\n observer.next(true);\n }\n observer.complete();\n });\n });\n }\n fileWalker(dir, exclude = 'node_modules') {\n return new rxjs_1.Observable(observer => {\n this.filewalker(dir, (err, result) => {\n if (err) {\n observer.error(err);\n }\n else {\n observer.next(result);\n }\n observer.complete();\n }, exclude);\n });\n }\n filewalker(dir, done, exclude = 'node_modules') {\n let results = [];\n const fileWalker = this.filewalker.bind(this);\n fs_1.readdir(dir, (err, list) => {\n if (err) {\n return done(err);\n }\n let pending = list.length;\n if (!pending) {\n return done(null, results);\n }\n list.forEach(file => {\n file = path_1.resolve(dir, file);\n fs_1.stat(file, (err, stat) => {\n if (stat && stat.isDirectory()) {\n results.push(file);\n if (!file.includes(exclude)) {\n fileWalker(file, (err, res) => {\n results = results.concat(res);\n if (!--pending) {\n done(null, results);\n }\n }, exclude);\n }\n else if (!--pending) {\n done(null, results);\n }\n }\n else {\n results.push(file);\n if (!--pending) {\n done(null, results);\n }\n }\n });\n });\n });\n }\n};\n__decorate([\n injector_decorator_1.Injector(bootstrap_logger_1.BootstrapLogger),\n __metadata(\"design:type\", bootstrap_logger_1.BootstrapLogger)\n], FileService.prototype, \"logger\", void 0);\nFileService = __decorate([\n Service_1.Service()\n], FileService);\nexports.FileService = FileService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./file.service\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// import { createReadStream, createWriteStream } from 'fs';\n// import { createGzip, createGunzip } from 'zlib';\n// import { Observable } from 'rxjs';\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst index_1 = require(\"../config/index\");\nlet CompressionService = class CompressionService {\n // public gZipFile(input: string, output: string, options: PrivateCryptoModel = { cyperIv: '', algorithm: '', cyperKey: '' }) {\n // const config = this.config.config.experimental.crypto || options;\n // return Observable.create(observer => {\n // createReadStream(input)\n // .pipe(createGzip())\n // // .pipe(createCipheriv(config.algorithm, config.cyperKey, config.cyperIv))\n // .pipe(createWriteStream(output))\n // .on('finish', () => observer.next(true))\n // .on('error', (err) => observer.error(err));\n // });\n // }\n // public readGzipFile(input: string, output: string, options: PrivateCryptoModel = { cyperIv: '', algorithm: '', cyperKey: '' }) {\n // const config = this.config.config.experimental.crypto || options;\n // return Observable.create(observer => {\n // createReadStream(input)\n // // .pipe(createDecipheriv(config.algorithm, config.cyperKey, config.cyperIv))\n // .pipe(createGunzip())\n // .pipe(createWriteStream(output))\n // .on('finish', () => observer.next(true))\n // .on('error', (err) => observer.error(err));\n // });\n // }\n gZipAll() {\n // var archiver = require('archiver');\n // var output = createWriteStream('./example.tar.gz');\n // var archive = archiver('tar', {\n // gzip: true,\n // zlib: { level: 9 } // Sets the compression level.\n // });\n // archive.on('error', function (err) {\n // throw err;\n // });\n // // pipe archive data to the output file\n // archive.pipe(output);\n // // append files\n // archive.file('/path/to/file0.txt', { name: 'file0-or-change-this-whatever.txt' });\n // archive.file('/path/to/README.md', { name: 'foobar.md' });\n // // Wait for streams to complete\n // archive.finalize();\n }\n};\n__decorate([\n injector_decorator_1.Injector(index_1.ConfigService),\n __metadata(\"design:type\", index_1.ConfigService)\n], CompressionService.prototype, \"config\", void 0);\nCompressionService = __decorate([\n Service_1.Service()\n], CompressionService);\nexports.CompressionService = CompressionService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nconst childProcess = require(\"child_process\");\nlet NpmService = class NpmService {\n constructor() {\n this.packagesToDownload = new rxjs_1.BehaviorSubject([]);\n this.packages = [];\n }\n setPackages(packages) {\n this.packagesToDownload.next([\n ...this.packagesToDownload.getValue(),\n ...packages\n ]);\n }\n preparePackages() {\n const arr = this.packagesToDownload.getValue() || [];\n this.packages = [...new Set(arr.map(p => `${p.name}@${p.version}`))];\n }\n installPackages() {\n return new Promise((resolve, reject) => {\n this.preparePackages();\n if (this.child) {\n this.child.stdout.removeAllListeners('data');\n this.child.stderr.removeAllListeners('data');\n this.child.removeAllListeners('exit');\n this.child.kill();\n }\n console.log(`Installing npm packages on child process! ${this.packages.toString()}`);\n this.child = childProcess.spawn('npm', ['i', ...this.packages]);\n this.child.stdout.on('data', data => process.stdout.write(data));\n this.child.stderr.on('data', data => {\n process.stdout.write(data);\n // reject(data)\n });\n this.child.on('exit', code => {\n console.log(`Child process exited with code ${code}`);\n console.log(`Installing npm packages DONE! ${this.packages.toString()}`);\n this.child = null;\n });\n });\n }\n};\nNpmService = __decorate([\n Service_1.Service()\n], NpmService);\nexports.NpmService = NpmService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IPFS_PROVIDERS = [\n {\n name: 'cloudflare',\n link: 'https://cloudflare-ipfs.com/ipfs/'\n },\n {\n name: 'main-ipfs-node',\n link: 'https://ipfs.io/ipfs/'\n },\n {\n name: 'infura',\n link: 'https://ipfs.infura.io/ipfs/'\n },\n {\n name: 'local',\n link: 'http://127.0.0.1:8080/ipfs/'\n }\n];\n","import { global, isBrowser, isWorker } from './common.js';\r\nimport SystemJSLoader from './systemjs-loader.js';\r\n\r\nSystemJSLoader.prototype.version = VERSION;\r\n\r\nvar System = new SystemJSLoader();\r\n\r\n// only set the global System on the global in browsers\r\nif (isBrowser || isWorker)\r\n global.SystemJS = global.System = System;\r\n\r\nif (typeof module !== 'undefined' && module.exports)\r\n module.exports = System;\r\n","/*\r\n * Environment\r\n */\r\nexport var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';\r\nexport var isNode = typeof process !== 'undefined' && process.versions && process.versions.node;\r\nexport var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/);\r\n\r\nvar envGlobal = typeof self !== 'undefined' ? self : global;\r\nexport { envGlobal as global }\r\n\r\n/*\r\n * Simple Symbol() shim\r\n */\r\nvar hasSymbol = typeof Symbol !== 'undefined';\r\nexport function createSymbol (name) {\r\n return hasSymbol ? Symbol() : '@@' + name;\r\n}\r\n\r\nexport var toStringTag = hasSymbol && Symbol.toStringTag;\r\n\r\nexport function pathToFileUrl (filePath) {\r\n return 'file://' + (isWindows ? '/' : '') + (isWindows ? filePath.replace(/\\\\/g, '/') : filePath);\r\n}\r\n\r\nexport function fileUrlToPath (fileUrl) {\r\n if (fileUrl.substr(0, 7) !== 'file://')\r\n throw new RangeError(fileUrl + ' is not a valid file url');\r\n if (isWindows)\r\n return fileUrl.substr(8).replace(/\\\\/g, '/');\r\n else\r\n return fileUrl.substr(7);\r\n}\r\n\r\n/*\r\n * Environment baseURI\r\n */\r\nexport var baseURI;\r\n\r\n// environent baseURI detection\r\nif (typeof document != 'undefined' && document.getElementsByTagName) {\r\n baseURI = document.baseURI;\r\n\r\n if (!baseURI) {\r\n var bases = document.getElementsByTagName('base');\r\n baseURI = bases[0] && bases[0].href || window.location.href;\r\n }\r\n}\r\nelse if (typeof location != 'undefined') {\r\n baseURI = location.href;\r\n}\r\n\r\n// sanitize out the hash and querystring\r\nif (baseURI) {\r\n baseURI = baseURI.split('#')[0].split('?')[0];\r\n var slashIndex = baseURI.lastIndexOf('/');\r\n if (slashIndex !== -1)\r\n baseURI = baseURI.substr(0, slashIndex + 1);\r\n}\r\nelse if (typeof process !== 'undefined' && process.cwd) {\r\n baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd();\r\n if (isWindows)\r\n baseURI = baseURI.replace(/\\\\/g, '/');\r\n}\r\nelse {\r\n throw new TypeError('No environment baseURI');\r\n}\r\n\r\n// ensure baseURI has trailing \"/\"\r\nif (baseURI[baseURI.length - 1] !== '/')\r\n baseURI += '/';\r\n\r\n/*\r\n * LoaderError with chaining for loader stacks\r\n */\r\nvar errArgs = new Error(0, '_').fileName == '_';\r\nfunction LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) {\r\n // Convert file:/// URLs to paths in Node\r\n if (!isBrowser)\r\n newMessage = newMessage.replace(isWindows ? /file:\\/\\/\\//g : /file:\\/\\//g, '');\r\n\r\n var message = (childErr.message || childErr) + '\\n ' + newMessage;\r\n\r\n var err;\r\n if (errArgs && childErr.fileName)\r\n err = new Error(message, childErr.fileName, childErr.lineNumber);\r\n else\r\n err = new Error(message);\r\n\r\n\r\n var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack;\r\n\r\n if (isNode)\r\n // node doesn't show the message otherwise\r\n err.stack = message + '\\n ' + stack;\r\n else\r\n err.stack = stack;\r\n\r\n err.originalErr = childErr.originalErr || childErr;\r\n\r\n return err;\r\n}\r\nexport { LoaderError__Check_error_message_for_loader_stack as addToError }\r\n","import { isNode } from './common.js';\r\n\r\n/*\r\n * Optimized URL normalization assuming a syntax-valid URL parent\r\n */\r\nfunction throwResolveError (relUrl, parentUrl) {\r\n throw new RangeError('Unable to resolve \"' + relUrl + '\" to ' + parentUrl);\r\n}\r\nvar backslashRegEx = /\\\\/g;\r\nexport function resolveIfNotPlain (relUrl, parentUrl) {\r\n if (relUrl[0] === ' ' || relUrl[relUrl.length - 1] === ' ')\r\n relUrl = relUrl.trim();\r\n var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1);\r\n\r\n var firstChar = relUrl[0];\r\n var secondChar = relUrl[1];\r\n\r\n // protocol-relative\r\n if (firstChar === '/' && secondChar === '/') {\r\n if (!parentProtocol)\r\n throwResolveError(relUrl, parentUrl);\r\n if (relUrl.indexOf('\\\\') !== -1)\r\n relUrl = relUrl.replace(backslashRegEx, '/');\r\n return parentProtocol + relUrl;\r\n }\r\n // relative-url\r\n else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) ||\r\n relUrl.length === 1 && (relUrl += '/')) ||\r\n firstChar === '/') {\r\n if (relUrl.indexOf('\\\\') !== -1)\r\n relUrl = relUrl.replace(backslashRegEx, '/');\r\n var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/';\r\n\r\n // read pathname from parent if a URL\r\n // pathname taken to be part after leading \"/\"\r\n var pathname;\r\n if (parentIsPlain) {\r\n // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname\r\n if (parentUrl === undefined)\r\n throwResolveError(relUrl, parentUrl);\r\n pathname = parentUrl;\r\n }\r\n else if (parentUrl[parentProtocol.length + 1] === '/') {\r\n // resolving to a :// so we need to read out the auth and host\r\n if (parentProtocol !== 'file:') {\r\n pathname = parentUrl.substr(parentProtocol.length + 2);\r\n pathname = pathname.substr(pathname.indexOf('/') + 1);\r\n }\r\n else {\r\n pathname = parentUrl.substr(8);\r\n }\r\n }\r\n else {\r\n // resolving to :/ so pathname is the /... part\r\n pathname = parentUrl.substr(parentProtocol.length + 1);\r\n }\r\n\r\n if (firstChar === '/') {\r\n if (parentIsPlain)\r\n throwResolveError(relUrl, parentUrl);\r\n else\r\n return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl;\r\n }\r\n\r\n // join together and split for removal of .. and . segments\r\n // looping the string instead of anything fancy for perf reasons\r\n // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain\r\n var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl;\r\n\r\n var output = [];\r\n var segmentIndex = -1;\r\n\r\n for (var i = 0; i < segmented.length; i++) {\r\n // busy reading a segment - only terminate on '/'\r\n if (segmentIndex !== -1) {\r\n if (segmented[i] === '/') {\r\n output.push(segmented.substring(segmentIndex, i + 1));\r\n segmentIndex = -1;\r\n }\r\n continue;\r\n }\r\n\r\n // new segment - check if it is relative\r\n if (segmented[i] === '.') {\r\n // ../ segment\r\n if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {\r\n output.pop();\r\n i += 2;\r\n }\r\n // ./ segment\r\n else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {\r\n i += 1;\r\n }\r\n else {\r\n // the start of a new segment as below\r\n segmentIndex = i;\r\n continue;\r\n }\r\n\r\n // this is the plain URI backtracking error (../, package:x -> error)\r\n if (parentIsPlain && output.length === 0)\r\n throwResolveError(relUrl, parentUrl);\r\n\r\n continue;\r\n }\r\n\r\n // it is the start of a new segment\r\n segmentIndex = i;\r\n }\r\n // finish reading out the last segment\r\n if (segmentIndex !== -1)\r\n output.push(segmented.substr(segmentIndex));\r\n\r\n return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join('');\r\n }\r\n\r\n // sanitizes and verifies (by returning undefined if not a valid URL-like form)\r\n // Windows filepath compatibility is an added convenience here\r\n var protocolIndex = relUrl.indexOf(':');\r\n if (protocolIndex !== -1) {\r\n if (isNode) {\r\n // C:\\x becomes file:///c:/x (we don't support C|\\x)\r\n if (relUrl[1] === ':' && relUrl[2] === '\\\\' && relUrl[0].match(/[a-z]/i))\r\n return 'file:///' + relUrl.replace(backslashRegEx, '/');\r\n }\r\n return relUrl;\r\n }\r\n}\r\n","import { addToError, createSymbol, toStringTag } from './common.js';\r\n\r\nexport { Loader, ModuleNamespace, REGISTRY }\r\n\r\nvar resolvedPromise = Promise.resolve();\r\n\r\n/*\r\n * Simple Array values shim\r\n */\r\nfunction arrayValues (arr) {\r\n if (arr.values)\r\n return arr.values();\r\n\r\n if (typeof Symbol === 'undefined' || !Symbol.iterator)\r\n throw new Error('Symbol.iterator not supported in this browser');\r\n\r\n var iterable = {};\r\n iterable[Symbol.iterator] = function () {\r\n var keys = Object.keys(arr);\r\n var keyIndex = 0;\r\n return {\r\n next: function () {\r\n if (keyIndex < keys.length)\r\n return {\r\n value: arr[keys[keyIndex++]],\r\n done: false\r\n };\r\n else\r\n return {\r\n value: undefined,\r\n done: true\r\n };\r\n }\r\n };\r\n };\r\n return iterable;\r\n}\r\n\r\n/*\r\n * 3. Reflect.Loader\r\n *\r\n * We skip the entire native internal pipeline, just providing the bare API\r\n */\r\n// 3.1.1\r\nfunction Loader () {\r\n this.registry = new Registry();\r\n}\r\n// 3.3.1\r\nLoader.prototype.constructor = Loader;\r\n\r\nfunction ensureInstantiated (module) {\r\n if (module === undefined)\r\n return;\r\n if (module instanceof ModuleNamespace === false && module[toStringTag] !== 'module')\r\n throw new TypeError('Module instantiation did not return a valid namespace object.');\r\n return module;\r\n}\r\n\r\n// 3.3.2\r\nLoader.prototype.import = function (key, parent) {\r\n if (typeof key !== 'string')\r\n throw new TypeError('Loader import method must be passed a module key string');\r\n // custom resolveInstantiate combined hook for better perf\r\n var loader = this;\r\n return resolvedPromise\r\n .then(function () {\r\n return loader[RESOLVE_INSTANTIATE](key, parent);\r\n })\r\n .then(ensureInstantiated)\r\n //.then(Module.evaluate)\r\n .catch(function (err) {\r\n throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));\r\n });\r\n};\r\n// 3.3.3\r\nvar RESOLVE = Loader.resolve = createSymbol('resolve');\r\n\r\n/*\r\n * Combined resolve / instantiate hook\r\n *\r\n * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described\r\n * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted.\r\n *\r\n * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid\r\n * the need for double registry lookups as a performance optimization.\r\n */\r\nvar RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate');\r\n\r\n// default resolveInstantiate is just to call resolve and then get from the registry\r\n// this provides compatibility for the resolveInstantiate optimization\r\nLoader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) {\r\n var loader = this;\r\n return loader.resolve(key, parent)\r\n .then(function (resolved) {\r\n return loader.registry.get(resolved);\r\n });\r\n};\r\n\r\nfunction ensureResolution (resolvedKey) {\r\n if (resolvedKey === undefined)\r\n throw new RangeError('No resolution found.');\r\n return resolvedKey;\r\n}\r\n\r\nLoader.prototype.resolve = function (key, parent) {\r\n var loader = this;\r\n return resolvedPromise\r\n .then(function() {\r\n return loader[RESOLVE](key, parent);\r\n })\r\n .then(ensureResolution)\r\n .catch(function (err) {\r\n throw addToError(err, 'Resolving ' + key + (parent ? ' to ' + parent : ''));\r\n });\r\n};\r\n\r\n// 3.3.4 (import without evaluate)\r\n// this is not documented because the use of deferred evaluation as in Module.evaluate is not\r\n// documented, as it is not considered a stable feature to be encouraged\r\n// Loader.prototype.load may well be deprecated if this stays disabled\r\n/* Loader.prototype.load = function (key, parent) {\r\n return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key))\r\n .catch(function (err) {\r\n throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));\r\n });\r\n}; */\r\n\r\n/*\r\n * 4. Registry\r\n *\r\n * Instead of structuring through a Map, just use a dictionary object\r\n * We throw for construction attempts so this doesn't affect the public API\r\n *\r\n * Registry has been adjusted to use Namespace objects over ModuleStatus objects\r\n * as part of simplifying loader API implementation\r\n */\r\nvar iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator;\r\nvar REGISTRY = createSymbol('registry');\r\nfunction Registry() {\r\n this[REGISTRY] = {};\r\n}\r\n// 4.4.1\r\nif (iteratorSupport) {\r\n // 4.4.2\r\n Registry.prototype[Symbol.iterator] = function () {\r\n return this.entries()[Symbol.iterator]();\r\n };\r\n\r\n // 4.4.3\r\n Registry.prototype.entries = function () {\r\n var registry = this[REGISTRY];\r\n return arrayValues(Object.keys(registry).map(function (key) {\r\n return [key, registry[key]];\r\n }));\r\n };\r\n}\r\n\r\n// 4.4.4\r\nRegistry.prototype.keys = function () {\r\n return arrayValues(Object.keys(this[REGISTRY]));\r\n};\r\n// 4.4.5\r\nRegistry.prototype.values = function () {\r\n var registry = this[REGISTRY];\r\n return arrayValues(Object.keys(registry).map(function (key) {\r\n return registry[key];\r\n }));\r\n};\r\n// 4.4.6\r\nRegistry.prototype.get = function (key) {\r\n return this[REGISTRY][key];\r\n};\r\n// 4.4.7\r\nRegistry.prototype.set = function (key, namespace) {\r\n if (!(namespace instanceof ModuleNamespace || namespace[toStringTag] === 'module'))\r\n throw new Error('Registry must be set with an instance of Module Namespace');\r\n this[REGISTRY][key] = namespace;\r\n return this;\r\n};\r\n// 4.4.8\r\nRegistry.prototype.has = function (key) {\r\n return Object.hasOwnProperty.call(this[REGISTRY], key);\r\n};\r\n// 4.4.9\r\nRegistry.prototype.delete = function (key) {\r\n if (Object.hasOwnProperty.call(this[REGISTRY], key)) {\r\n delete this[REGISTRY][key];\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n/*\r\n * Simple ModuleNamespace Exotic object based on a baseObject\r\n * We export this for allowing a fast-path for module namespace creation over Module descriptors\r\n */\r\n// var EVALUATE = createSymbol('evaluate');\r\nvar BASE_OBJECT = createSymbol('baseObject');\r\n\r\n// 8.3.1 Reflect.Module\r\n/*\r\n * Best-effort simplified non-spec implementation based on\r\n * a baseObject referenced via getters.\r\n *\r\n * Allows:\r\n *\r\n * loader.registry.set('x', new Module({ default: 'x' }));\r\n *\r\n * Optional evaluation function provides experimental Module.evaluate\r\n * support for non-executed modules in registry.\r\n */\r\nfunction ModuleNamespace (baseObject/*, evaluate*/) {\r\n Object.defineProperty(this, BASE_OBJECT, {\r\n value: baseObject\r\n });\r\n\r\n // evaluate defers namespace population\r\n /* if (evaluate) {\r\n Object.defineProperty(this, EVALUATE, {\r\n value: evaluate,\r\n configurable: true,\r\n writable: true\r\n });\r\n }\r\n else { */\r\n Object.keys(baseObject).forEach(extendNamespace, this);\r\n //}\r\n};\r\n// 8.4.2\r\nModuleNamespace.prototype = Object.create(null);\r\n\r\nif (toStringTag)\r\n Object.defineProperty(ModuleNamespace.prototype, toStringTag, {\r\n value: 'Module'\r\n });\r\n\r\nfunction extendNamespace (key) {\r\n Object.defineProperty(this, key, {\r\n enumerable: true,\r\n get: function () {\r\n return this[BASE_OBJECT][key];\r\n }\r\n });\r\n}\r\n\r\n/* function doEvaluate (evaluate, context) {\r\n try {\r\n evaluate.call(context);\r\n }\r\n catch (e) {\r\n return e;\r\n }\r\n}\r\n\r\n// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable\r\nModule.evaluate = function (ns) {\r\n var evaluate = ns[EVALUATE];\r\n if (evaluate) {\r\n ns[EVALUATE] = undefined;\r\n var err = doEvaluate(evaluate);\r\n if (err) {\r\n // cache the error\r\n ns[EVALUATE] = function () {\r\n throw err;\r\n };\r\n throw err;\r\n }\r\n Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns);\r\n }\r\n // make chainable\r\n return ns;\r\n}; */\r\n","import { Loader, ModuleNamespace, REGISTRY } from './loader-polyfill.js';\r\nimport { resolveIfNotPlain } from './resolve.js';\r\nimport { addToError, global, createSymbol, baseURI, toStringTag } from './common.js';\r\n\r\nexport default RegisterLoader;\r\n\r\nvar resolvedPromise = Promise.resolve();\r\nvar emptyArray = [];\r\n\r\n/*\r\n * Register Loader\r\n *\r\n * Builds directly on top of loader polyfill to provide:\r\n * - loader.register support\r\n * - hookable higher-level resolve\r\n * - instantiate hook returning a ModuleNamespace or undefined for es module loading\r\n * - loader error behaviour as in HTML and loader specs, caching load and eval errors separately\r\n * - build tracing support by providing a .trace=true and .loads object format\r\n */\r\n\r\nvar REGISTER_INTERNAL = createSymbol('register-internal');\r\n\r\nfunction RegisterLoader () {\r\n Loader.call(this);\r\n\r\n var registryDelete = this.registry.delete;\r\n this.registry.delete = function (key) {\r\n var deleted = registryDelete.call(this, key);\r\n\r\n // also delete from register registry if linked\r\n if (records.hasOwnProperty(key) && !records[key].linkRecord) {\r\n delete records[key];\r\n deleted = true;\r\n }\r\n\r\n return deleted;\r\n };\r\n\r\n var records = {};\r\n\r\n this[REGISTER_INTERNAL] = {\r\n // last anonymous System.register call\r\n lastRegister: undefined,\r\n // in-flight es module load records\r\n records: records\r\n };\r\n\r\n // tracing\r\n this.trace = false;\r\n}\r\n\r\nRegisterLoader.prototype = Object.create(Loader.prototype);\r\nRegisterLoader.prototype.constructor = RegisterLoader;\r\n\r\nvar INSTANTIATE = RegisterLoader.instantiate = createSymbol('instantiate');\r\n\r\n// default normalize is the WhatWG style normalizer\r\nRegisterLoader.prototype[RegisterLoader.resolve = Loader.resolve] = function (key, parentKey) {\r\n return resolveIfNotPlain(key, parentKey || baseURI);\r\n};\r\n\r\nRegisterLoader.prototype[INSTANTIATE] = function (key, processAnonRegister) {};\r\n\r\n// once evaluated, the linkRecord is set to undefined leaving just the other load record properties\r\n// this allows tracking new binding listeners for es modules through importerSetters\r\n// for dynamic modules, the load record is removed entirely.\r\nfunction createLoadRecord (state, key, registration) {\r\n return state.records[key] = {\r\n key: key,\r\n\r\n // defined System.register cache\r\n registration: registration,\r\n\r\n // module namespace object\r\n module: undefined,\r\n\r\n // es-only\r\n // this sticks around so new module loads can listen to binding changes\r\n // for already-loaded modules by adding themselves to their importerSetters\r\n importerSetters: undefined,\r\n\r\n loadError: undefined,\r\n evalError: undefined,\r\n\r\n // in-flight linking record\r\n linkRecord: {\r\n // promise for instantiated\r\n instantiatePromise: undefined,\r\n dependencies: undefined,\r\n execute: undefined,\r\n executingRequire: false,\r\n\r\n // underlying module object bindings\r\n moduleObj: undefined,\r\n\r\n // es only, also indicates if es or not\r\n setters: undefined,\r\n\r\n // promise for instantiated dependencies (dependencyInstantiations populated)\r\n depsInstantiatePromise: undefined,\r\n // will be the array of dependency load record or a module namespace\r\n dependencyInstantiations: undefined,\r\n\r\n // top-level await!\r\n evaluatePromise: undefined,\r\n\r\n // NB optimization and way of ensuring module objects in setters\r\n // indicates setters which should run pre-execution of that dependency\r\n // setters is then just for completely executed module objects\r\n // alternatively we just pass the partially filled module objects as\r\n // arguments into the execute function\r\n // hoisted: undefined\r\n }\r\n };\r\n}\r\n\r\nRegisterLoader.prototype[Loader.resolveInstantiate] = function (key, parentKey) {\r\n var loader = this;\r\n var state = this[REGISTER_INTERNAL];\r\n var registry = this.registry[REGISTRY];\r\n\r\n return resolveInstantiate(loader, key, parentKey, registry, state)\r\n .then(function (instantiated) {\r\n if (instantiated instanceof ModuleNamespace || instantiated[toStringTag] === 'module')\r\n return instantiated;\r\n\r\n // resolveInstantiate always returns a load record with a link record and no module value\r\n var link = instantiated.linkRecord;\r\n\r\n // if already beaten to done, return\r\n if (!link) {\r\n if (instantiated.module)\r\n return instantiated.module;\r\n throw instantiated.evalError;\r\n }\r\n\r\n return deepInstantiateDeps(loader, instantiated, link, registry, state)\r\n .then(function () {\r\n return ensureEvaluate(loader, instantiated, link, registry, state);\r\n });\r\n });\r\n};\r\n\r\nfunction resolveInstantiate (loader, key, parentKey, registry, state) {\r\n // normalization shortpath for already-normalized key\r\n // could add a plain name filter, but doesn't yet seem necessary for perf\r\n var module = registry[key];\r\n if (module)\r\n return Promise.resolve(module);\r\n\r\n var load = state.records[key];\r\n\r\n // already linked but not in main registry is ignored\r\n if (load && !load.module) {\r\n if (load.loadError)\r\n return Promise.reject(load.loadError);\r\n return instantiate(loader, load, load.linkRecord, registry, state);\r\n }\r\n\r\n return loader.resolve(key, parentKey)\r\n .then(function (resolvedKey) {\r\n // main loader registry always takes preference\r\n module = registry[resolvedKey];\r\n if (module)\r\n return module;\r\n\r\n load = state.records[resolvedKey];\r\n\r\n // already has a module value but not already in the registry (load.module)\r\n // means it was removed by registry.delete, so we should\r\n // disgard the current load record creating a new one over it\r\n // but keep any existing registration\r\n if (!load || load.module)\r\n load = createLoadRecord(state, resolvedKey, load && load.registration);\r\n\r\n if (load.loadError)\r\n return Promise.reject(load.loadError);\r\n\r\n var link = load.linkRecord;\r\n if (!link)\r\n return load;\r\n\r\n return instantiate(loader, load, link, registry, state);\r\n });\r\n}\r\n\r\nfunction createProcessAnonRegister (loader, load, state) {\r\n return function () {\r\n var lastRegister = state.lastRegister;\r\n\r\n if (!lastRegister)\r\n return !!load.registration;\r\n\r\n state.lastRegister = undefined;\r\n load.registration = lastRegister;\r\n\r\n return true;\r\n };\r\n}\r\n\r\nfunction instantiate (loader, load, link, registry, state) {\r\n return link.instantiatePromise || (link.instantiatePromise =\r\n // if there is already an existing registration, skip running instantiate\r\n (load.registration ? resolvedPromise : resolvedPromise.then(function () {\r\n state.lastRegister = undefined;\r\n return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state));\r\n }))\r\n .then(function (instantiation) {\r\n // direct module return from instantiate -> we're done\r\n if (instantiation !== undefined) {\r\n if (!(instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module'))\r\n throw new TypeError('Instantiate did not return a valid Module object.');\r\n\r\n delete state.records[load.key];\r\n if (loader.trace)\r\n traceLoad(loader, load, link);\r\n return registry[load.key] = instantiation;\r\n }\r\n\r\n // run the cached loader.register declaration if there is one\r\n var registration = load.registration;\r\n // clear to allow new registrations for future loads (combined with registry delete)\r\n load.registration = undefined;\r\n if (!registration)\r\n throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.');\r\n\r\n link.dependencies = registration[0];\r\n\r\n load.importerSetters = [];\r\n\r\n link.moduleObj = {};\r\n\r\n // process System.registerDynamic declaration\r\n if (registration[2]) {\r\n link.moduleObj.default = link.moduleObj.__useDefault = {};\r\n link.executingRequire = registration[1];\r\n link.execute = registration[2];\r\n }\r\n\r\n // process System.register declaration\r\n else {\r\n registerDeclarative(loader, load, link, registration[1]);\r\n }\r\n\r\n return load;\r\n })\r\n .catch(function (err) {\r\n load.linkRecord = undefined;\r\n throw load.loadError = load.loadError || addToError(err, 'Instantiating ' + load.key);\r\n }));\r\n}\r\n\r\n// like resolveInstantiate, but returning load records for linking\r\nfunction resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) {\r\n // normalization shortpaths for already-normalized key\r\n // DISABLED to prioritise consistent resolver calls\r\n // could add a plain name filter, but doesn't yet seem necessary for perf\r\n /* var load = state.records[key];\r\n var module = registry[key];\r\n\r\n if (module) {\r\n if (traceDepMap)\r\n traceDepMap[key] = key;\r\n\r\n // registry authority check in case module was deleted or replaced in main registry\r\n if (load && load.module && load.module === module)\r\n return load;\r\n else\r\n return module;\r\n }\r\n\r\n // already linked but not in main registry is ignored\r\n if (load && !load.module) {\r\n if (traceDepMap)\r\n traceDepMap[key] = key;\r\n return instantiate(loader, load, load.linkRecord, registry, state);\r\n } */\r\n return loader.resolve(key, parentKey)\r\n .then(function (resolvedKey) {\r\n if (traceDepMap)\r\n traceDepMap[key] = resolvedKey;\r\n\r\n // normalization shortpaths for already-normalized key\r\n var load = state.records[resolvedKey];\r\n var module = registry[resolvedKey];\r\n\r\n // main loader registry always takes preference\r\n if (module && (!load || load.module && module !== load.module))\r\n return module;\r\n\r\n if (load && load.loadError)\r\n throw load.loadError;\r\n\r\n // already has a module value but not already in the registry (load.module)\r\n // means it was removed by registry.delete, so we should\r\n // disgard the current load record creating a new one over it\r\n // but keep any existing registration\r\n if (!load || !module && load.module)\r\n load = createLoadRecord(state, resolvedKey, load && load.registration);\r\n\r\n var link = load.linkRecord;\r\n if (!link)\r\n return load;\r\n\r\n return instantiate(loader, load, link, registry, state);\r\n });\r\n}\r\n\r\nfunction traceLoad (loader, load, link) {\r\n loader.loads = loader.loads || {};\r\n loader.loads[load.key] = {\r\n key: load.key,\r\n deps: link.dependencies,\r\n dynamicDeps: [],\r\n depMap: link.depMap || {}\r\n };\r\n}\r\n\r\n/*\r\n * Convert a CJS module.exports into a valid object for new Module:\r\n *\r\n * new Module(getEsModule(module.exports))\r\n *\r\n * Sets the default value to the module, while also reading off named exports carefully.\r\n */\r\nfunction registerDeclarative (loader, load, link, declare) {\r\n var moduleObj = link.moduleObj;\r\n var importerSetters = load.importerSetters;\r\n\r\n var definedExports = false;\r\n\r\n // closure especially not based on link to allow link record disposal\r\n var declared = declare.call(global, function (name, value) {\r\n if (typeof name === 'object') {\r\n var changed = false;\r\n for (var p in name) {\r\n value = name[p];\r\n if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) {\r\n changed = true;\r\n moduleObj[p] = value;\r\n }\r\n }\r\n if (changed === false)\r\n return value;\r\n }\r\n else {\r\n if ((definedExports || name in moduleObj) && moduleObj[name] === value)\r\n return value;\r\n moduleObj[name] = value;\r\n }\r\n\r\n for (var i = 0; i < importerSetters.length; i++)\r\n importerSetters[i](moduleObj);\r\n\r\n return value;\r\n }, new ContextualLoader(loader, load.key));\r\n\r\n link.setters = declared.setters || [];\r\n link.execute = declared.execute;\r\n if (declared.exports) {\r\n link.moduleObj = moduleObj = declared.exports;\r\n definedExports = true;\r\n }\r\n}\r\n\r\nfunction instantiateDeps (loader, load, link, registry, state) {\r\n if (link.depsInstantiatePromise)\r\n return link.depsInstantiatePromise;\r\n\r\n var depsInstantiatePromises = Array(link.dependencies.length);\r\n\r\n for (var i = 0; i < link.dependencies.length; i++)\r\n depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {}));\r\n\r\n var depsInstantiatePromise = Promise.all(depsInstantiatePromises)\r\n .then(function (dependencyInstantiations) {\r\n link.dependencyInstantiations = dependencyInstantiations;\r\n\r\n // run setters to set up bindings to instantiated dependencies\r\n if (link.setters) {\r\n for (var i = 0; i < dependencyInstantiations.length; i++) {\r\n var setter = link.setters[i];\r\n if (setter) {\r\n var instantiation = dependencyInstantiations[i];\r\n\r\n if (instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module') {\r\n setter(instantiation);\r\n }\r\n else {\r\n if (instantiation.loadError)\r\n throw instantiation.loadError;\r\n setter(instantiation.module || instantiation.linkRecord.moduleObj);\r\n // this applies to both es and dynamic registrations\r\n if (instantiation.importerSetters)\r\n instantiation.importerSetters.push(setter);\r\n }\r\n }\r\n }\r\n }\r\n\r\n return load;\r\n });\r\n\r\n if (loader.trace)\r\n depsInstantiatePromise = depsInstantiatePromise.then(function () {\r\n traceLoad(loader, load, link);\r\n return load;\r\n });\r\n\r\n depsInstantiatePromise = depsInstantiatePromise.catch(function (err) {\r\n // throw up the instantiateDeps stack\r\n link.depsInstantiatePromise = undefined;\r\n throw addToError(err, 'Loading ' + load.key);\r\n });\r\n\r\n depsInstantiatePromise.catch(function () {});\r\n\r\n return link.depsInstantiatePromise = depsInstantiatePromise;\r\n}\r\n\r\nfunction deepInstantiateDeps (loader, load, link, registry, state) {\r\n var seen = [];\r\n function addDeps (load, link) {\r\n if (!link)\r\n return resolvedPromise;\r\n if (seen.indexOf(load) !== -1)\r\n return resolvedPromise;\r\n seen.push(load);\r\n \r\n return instantiateDeps(loader, load, link, registry, state)\r\n .then(function () {\r\n var depPromises;\r\n for (var i = 0; i < link.dependencies.length; i++) {\r\n var depLoad = link.dependencyInstantiations[i];\r\n if (!(depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module')) {\r\n depPromises = depPromises || [];\r\n depPromises.push(addDeps(depLoad, depLoad.linkRecord));\r\n }\r\n }\r\n if (depPromises)\r\n return Promise.all(depPromises);\r\n });\r\n };\r\n\r\n return addDeps(load, link);\r\n}\r\n\r\n/*\r\n * System.register\r\n */\r\nRegisterLoader.prototype.register = function (key, deps, declare) {\r\n var state = this[REGISTER_INTERNAL];\r\n\r\n // anonymous modules get stored as lastAnon\r\n if (declare === undefined) {\r\n state.lastRegister = [key, deps, undefined];\r\n }\r\n\r\n // everything else registers into the register cache\r\n else {\r\n var load = state.records[key] || createLoadRecord(state, key, undefined);\r\n load.registration = [deps, declare, undefined];\r\n }\r\n};\r\n\r\n/*\r\n * System.registerDyanmic\r\n */\r\nRegisterLoader.prototype.registerDynamic = function (key, deps, executingRequire, execute) {\r\n var state = this[REGISTER_INTERNAL];\r\n\r\n // anonymous modules get stored as lastAnon\r\n if (typeof key !== 'string') {\r\n state.lastRegister = [key, deps, executingRequire];\r\n }\r\n\r\n // everything else registers into the register cache\r\n else {\r\n var load = state.records[key] || createLoadRecord(state, key, undefined);\r\n load.registration = [deps, executingRequire, execute];\r\n }\r\n};\r\n\r\n// ContextualLoader class\r\n// backwards-compatible with previous System.register context argument by exposing .id, .key\r\nfunction ContextualLoader (loader, key) {\r\n this.loader = loader;\r\n this.key = this.id = key;\r\n this.meta = {\r\n url: key\r\n // scriptElement: null\r\n };\r\n}\r\n/*ContextualLoader.prototype.constructor = function () {\r\n throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.');\r\n};*/\r\nContextualLoader.prototype.import = function (key) {\r\n if (this.loader.trace)\r\n this.loader.loads[this.key].dynamicDeps.push(key);\r\n return this.loader.import(key, this.key);\r\n};\r\n/*ContextualLoader.prototype.resolve = function (key) {\r\n return this.loader.resolve(key, this.key);\r\n};*/\r\n\r\nfunction ensureEvaluate (loader, load, link, registry, state) {\r\n if (load.module)\r\n return load.module;\r\n if (load.evalError)\r\n throw load.evalError;\r\n if (link.evaluatePromise)\r\n return link.evaluatePromise;\r\n\r\n if (link.setters) {\r\n var evaluatePromise = doEvaluateDeclarative(loader, load, link, registry, state, [load]);\r\n if (evaluatePromise)\r\n return evaluatePromise;\r\n }\r\n else {\r\n doEvaluateDynamic(loader, load, link, registry, state, [load]);\r\n }\r\n return load.module;\r\n}\r\n\r\nfunction makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) {\r\n // we can only require from already-known dependencies\r\n return function (name) {\r\n for (var i = 0; i < dependencies.length; i++) {\r\n if (dependencies[i] === name) {\r\n var depLoad = dependencyInstantiations[i];\r\n var module;\r\n\r\n if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') {\r\n module = depLoad;\r\n }\r\n else {\r\n if (depLoad.evalError)\r\n throw depLoad.evalError;\r\n if (depLoad.module === undefined && seen.indexOf(depLoad) === -1 && !depLoad.linkRecord.evaluatePromise) {\r\n if (depLoad.linkRecord.setters) {\r\n doEvaluateDeclarative(loader, depLoad, depLoad.linkRecord, registry, state, [depLoad]);\r\n }\r\n else {\r\n seen.push(depLoad);\r\n doEvaluateDynamic(loader, depLoad, depLoad.linkRecord, registry, state, seen);\r\n }\r\n }\r\n module = depLoad.module || depLoad.linkRecord.moduleObj;\r\n }\r\n\r\n return '__useDefault' in module ? module.__useDefault : module;\r\n }\r\n }\r\n throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key);\r\n };\r\n}\r\n\r\nfunction evalError (load, err) {\r\n load.linkRecord = undefined;\r\n var evalError = addToError(err, 'Evaluating ' + load.key);\r\n if (load.evalError === undefined)\r\n load.evalError = evalError;\r\n throw evalError;\r\n}\r\n\r\n// es modules evaluate dependencies first\r\n// returns the error if any\r\nfunction doEvaluateDeclarative (loader, load, link, registry, state, seen) {\r\n var depLoad, depLink;\r\n var depLoadPromises;\r\n for (var i = 0; i < link.dependencies.length; i++) {\r\n var depLoad = link.dependencyInstantiations[i];\r\n if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module')\r\n continue;\r\n\r\n // custom Module returned from instantiate\r\n depLink = depLoad.linkRecord;\r\n if (depLink) {\r\n if (depLoad.evalError) {\r\n evalError(load, depLoad.evalError);\r\n }\r\n else if (depLink.setters) {\r\n if (seen.indexOf(depLoad) === -1) {\r\n seen.push(depLoad);\r\n try {\r\n var depLoadPromise = doEvaluateDeclarative(loader, depLoad, depLink, registry, state, seen);\r\n }\r\n catch (e) {\r\n evalError(load, e);\r\n }\r\n if (depLoadPromise) {\r\n depLoadPromises = depLoadPromises || [];\r\n depLoadPromises.push(depLoadPromise.catch(function (err) {\r\n evalError(load, err);\r\n }));\r\n }\r\n }\r\n }\r\n else {\r\n try {\r\n doEvaluateDynamic(loader, depLoad, depLink, registry, state, [depLoad]);\r\n }\r\n catch (e) {\r\n evalError(load, e);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (depLoadPromises)\r\n return link.evaluatePromise = Promise.all(depLoadPromises)\r\n .then(function () {\r\n if (link.execute) {\r\n // ES System.register execute\r\n // \"this\" is null in ES\r\n try {\r\n var execPromise = link.execute.call(nullContext);\r\n }\r\n catch (e) {\r\n evalError(load, e);\r\n }\r\n if (execPromise)\r\n return execPromise.catch(function (e) {\r\n evalError(load, e);\r\n })\r\n .then(function () {\r\n load.linkRecord = undefined;\r\n return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);\r\n });\r\n }\r\n \r\n // dispose link record\r\n load.linkRecord = undefined;\r\n registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);\r\n });\r\n\r\n if (link.execute) {\r\n // ES System.register execute\r\n // \"this\" is null in ES\r\n try {\r\n var execPromise = link.execute.call(nullContext);\r\n }\r\n catch (e) {\r\n evalError(load, e);\r\n }\r\n if (execPromise)\r\n return link.evaluatePromise = execPromise.catch(function (e) {\r\n evalError(load, e);\r\n })\r\n .then(function () {\r\n load.linkRecord = undefined;\r\n return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);\r\n });\r\n }\r\n\r\n // dispose link record\r\n load.linkRecord = undefined;\r\n registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);\r\n}\r\n\r\n// non es modules explicitly call moduleEvaluate through require\r\nfunction doEvaluateDynamic (loader, load, link, registry, state, seen) {\r\n // System.registerDynamic execute\r\n // \"this\" is \"exports\" in CJS\r\n var module = { id: load.key };\r\n var moduleObj = link.moduleObj;\r\n Object.defineProperty(module, 'exports', {\r\n configurable: true,\r\n set: function (exports) {\r\n moduleObj.default = moduleObj.__useDefault = exports;\r\n },\r\n get: function () {\r\n return moduleObj.__useDefault;\r\n }\r\n });\r\n\r\n var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen);\r\n\r\n // evaluate deps first\r\n if (!link.executingRequire)\r\n for (var i = 0; i < link.dependencies.length; i++)\r\n require(link.dependencies[i]);\r\n\r\n try {\r\n var output = link.execute.call(global, require, moduleObj.default, module);\r\n if (output !== undefined)\r\n module.exports = output;\r\n }\r\n catch (e) {\r\n evalError(load, e);\r\n }\r\n\r\n load.linkRecord = undefined;\r\n\r\n // pick up defineProperty calls to module.exports when we can\r\n if (module.exports !== moduleObj.__useDefault)\r\n moduleObj.default = moduleObj.__useDefault = module.exports;\r\n\r\n var moduleDefault = moduleObj.default;\r\n\r\n // __esModule flag extension support via lifting\r\n if (moduleDefault && moduleDefault.__esModule) {\r\n for (var p in moduleDefault) {\r\n if (Object.hasOwnProperty.call(moduleDefault, p))\r\n moduleObj[p] = moduleDefault[p];\r\n }\r\n }\r\n\r\n registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);\r\n\r\n // run importer setters and clear them\r\n // this allows dynamic modules to update themselves into es modules\r\n // as soon as execution has completed\r\n if (load.importerSetters)\r\n for (var i = 0; i < load.importerSetters.length; i++)\r\n load.importerSetters[i](load.module);\r\n load.importerSetters = undefined;\r\n}\r\n\r\n// the closest we can get to call(undefined)\r\nvar nullContext = Object.create(null);\r\nif (Object.freeze)\r\n Object.freeze(nullContext);\r\n","import { resolveIfNotPlain } from 'es-module-loader/core/resolve.js';\r\nimport { baseURI, isBrowser, isWindows, addToError, global, createSymbol, toStringTag } from 'es-module-loader/core/common.js';\r\nimport RegisterLoader from 'es-module-loader/core/register-loader.js';\r\nimport { ModuleNamespace } from 'es-module-loader/core/loader-polyfill.js';\r\n\r\nexport { baseURI, isBrowser, isWindows, addToError, global, resolveIfNotPlain, ModuleNamespace }\r\n\r\nexport var resolvedPromise = Promise.resolve();\r\nexport function noop () {};\r\n\r\nexport var emptyModule = new ModuleNamespace({});\r\n\r\nexport function protectedCreateNamespace (bindings) {\r\n if (bindings) {\r\n if (bindings instanceof ModuleNamespace || bindings[toStringTag] === 'module')\r\n return bindings;\r\n\r\n if (bindings.__esModule)\r\n return new ModuleNamespace(bindings);\r\n }\r\n\r\n return new ModuleNamespace({ default: bindings, __useDefault: bindings });\r\n}\r\n\r\nexport function isModule (m) {\r\n return m instanceof ModuleNamespace || m[toStringTag] === 'module';\r\n}\r\n\r\nexport var CONFIG = createSymbol('loader-config');\r\nexport var METADATA = createSymbol('metadata');\r\nexport var PLAIN_RESOLVE = createSymbol('plain-resolve');\r\nexport var PLAIN_RESOLVE_SYNC = createSymbol('plain-resolve-sync');\r\n\r\nexport var isWorker = typeof window === 'undefined' && typeof self !== 'undefined' && typeof importScripts !== 'undefined';\r\n\r\nexport function warn (msg, force) {\r\n if (force || this.warnings && typeof console !== 'undefined' && console.warn)\r\n console.warn(msg);\r\n}\r\n\r\nexport function checkInstantiateWasm (loader, wasmBuffer, processAnonRegister) {\r\n var bytes = new Uint8Array(wasmBuffer);\r\n\r\n // detect by leading bytes\r\n // Can be (new Uint32Array(fetched))[0] === 0x6D736100 when working in Node\r\n if (bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115) {\r\n return WebAssembly.compile(wasmBuffer).then(function (m) {\r\n var deps = [];\r\n var setters = [];\r\n var importObj = {};\r\n\r\n // we can only set imports if supported (eg Safari doesnt support)\r\n if (WebAssembly.Module.imports)\r\n WebAssembly.Module.imports(m).forEach(function (i) {\r\n var key = i.module;\r\n setters.push(function (m) {\r\n importObj[key] = m;\r\n });\r\n if (deps.indexOf(key) === -1)\r\n deps.push(key);\r\n });\r\n loader.register(deps, function (_export) {\r\n return {\r\n setters: setters,\r\n execute: function () {\r\n _export(new WebAssembly.Instance(m, importObj).exports);\r\n }\r\n };\r\n });\r\n processAnonRegister();\r\n\r\n return true;\r\n });\r\n }\r\n\r\n return Promise.resolve(false);\r\n}\r\n\r\nvar parentModuleContext;\r\nexport function loadNodeModule (key, baseURL) {\r\n if (key[0] === '.')\r\n throw new Error('Node module ' + key + ' can\\'t be loaded as it is not a package require.');\r\n\r\n if (!parentModuleContext) {\r\n var Module = this._nodeRequire('module');\r\n var base = decodeURI(baseURL.substr(isWindows ? 8 : 7));\r\n parentModuleContext = new Module(base);\r\n parentModuleContext.paths = Module._nodeModulePaths(base);\r\n }\r\n return parentModuleContext.require(key);\r\n}\r\n\r\nexport function extend (a, b) {\r\n for (var p in b) {\r\n if (!Object.hasOwnProperty.call(b, p))\r\n continue;\r\n a[p] = b[p];\r\n }\r\n return a;\r\n}\r\n\r\nexport function prepend (a, b) {\r\n for (var p in b) {\r\n if (!Object.hasOwnProperty.call(b, p))\r\n continue;\r\n if (a[p] === undefined)\r\n a[p] = b[p];\r\n }\r\n return a;\r\n}\r\n\r\n// meta first-level extends where:\r\n// array + array appends\r\n// object + object extends\r\n// other properties replace\r\nexport function extendMeta (a, b, _prepend) {\r\n for (var p in b) {\r\n if (!Object.hasOwnProperty.call(b, p))\r\n continue;\r\n var val = b[p];\r\n if (a[p] === undefined)\r\n a[p] = val;\r\n else if (val instanceof Array && a[p] instanceof Array)\r\n a[p] = [].concat(_prepend ? val : a[p]).concat(_prepend ? a[p] : val);\r\n else if (typeof val == 'object' && val !== null && typeof a[p] == 'object')\r\n a[p] = (_prepend ? prepend : extend)(extend({}, a[p]), val);\r\n else if (!_prepend)\r\n a[p] = val;\r\n }\r\n}\r\n\r\nvar supportsPreload = false, supportsPrefetch = false;\r\nif (isBrowser)\r\n (function () {\r\n var relList = document.createElement('link').relList;\r\n if (relList && relList.supports) {\r\n supportsPrefetch = true;\r\n try {\r\n supportsPreload = relList.supports('preload');\r\n }\r\n catch (e) {}\r\n }\r\n })();\r\n\r\nexport function preloadScript (url) {\r\n // fallback to old fashioned image technique which still works in safari\r\n if (!supportsPreload && !supportsPrefetch) {\r\n var preloadImage = new Image();\r\n preloadImage.src = url;\r\n return;\r\n }\r\n\r\n var link = document.createElement('link');\r\n if (supportsPreload) {\r\n link.rel = 'preload';\r\n link.as = 'script';\r\n }\r\n else {\r\n // this works for all except Safari (detected by relList.supports lacking)\r\n link.rel = 'prefetch';\r\n }\r\n link.href = url;\r\n document.head.appendChild(link);\r\n}\r\n\r\nfunction workerImport (src, resolve, reject) {\r\n try {\r\n importScripts(src);\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n resolve();\r\n}\r\n\r\nif (isBrowser) {\r\n var onerror = window.onerror;\r\n window.onerror = function globalOnerror (msg, src) {\r\n if (onerror)\r\n onerror.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function scriptLoad (src, crossOrigin, integrity, resolve, reject) {\r\n // percent encode just \"#\" for HTTP requests\r\n src = src.replace(/#/g, '%23');\r\n\r\n // subresource integrity is not supported in web workers\r\n if (isWorker)\r\n return workerImport(src, resolve, reject);\r\n\r\n var script = document.createElement('script');\r\n script.type = 'text/javascript';\r\n script.charset = 'utf-8';\r\n script.async = true;\r\n\r\n if (crossOrigin)\r\n script.crossOrigin = crossOrigin;\r\n if (integrity)\r\n script.integrity = integrity;\r\n\r\n script.addEventListener('load', load, false);\r\n script.addEventListener('error', error, false);\r\n\r\n script.src = src;\r\n document.head.appendChild(script);\r\n\r\n function load () {\r\n resolve();\r\n cleanup();\r\n }\r\n\r\n // note this does not catch execution errors\r\n function error (err) {\r\n cleanup();\r\n reject(new Error('Fetching ' + src));\r\n }\r\n\r\n function cleanup () {\r\n script.removeEventListener('load', load, false);\r\n script.removeEventListener('error', error, false);\r\n document.head.removeChild(script);\r\n }\r\n}\r\n\r\nexport function readMemberExpression (p, value) {\r\n var pParts = p.split('.');\r\n while (pParts.length)\r\n value = value[pParts.shift()];\r\n return value;\r\n}\r\n\r\n// separate out paths cache as a baseURL lock process\r\nexport function applyPaths (baseURL, paths, key) {\r\n var mapMatch = getMapMatch(paths, key);\r\n if (mapMatch) {\r\n var target = paths[mapMatch] + key.substr(mapMatch.length);\r\n\r\n var resolved = resolveIfNotPlain(target, baseURI);\r\n if (resolved !== undefined)\r\n return resolved;\r\n\r\n return baseURL + target;\r\n }\r\n else if (key.indexOf(':') !== -1) {\r\n return key;\r\n }\r\n else {\r\n return baseURL + key;\r\n }\r\n}\r\n\r\nfunction checkMap (p) {\r\n var name = this.name;\r\n // can add ':' here if we want paths to match the behaviour of map\r\n if (name.substr(0, p.length) === p && (name.length === p.length || name[p.length] === '/' || p[p.length - 1] === '/' || p[p.length - 1] === ':')) {\r\n var curLen = p.split('/').length;\r\n if (curLen > this.len) {\r\n this.match = p;\r\n this.len = curLen;\r\n }\r\n }\r\n}\r\n\r\nexport function getMapMatch (map, name) {\r\n if (Object.hasOwnProperty.call(map, name))\r\n return name;\r\n\r\n var bestMatch = {\r\n name: name,\r\n match: undefined,\r\n len: 0\r\n };\r\n\r\n Object.keys(map).forEach(checkMap, bestMatch);\r\n\r\n return bestMatch.match;\r\n}\r\n\r\n// RegEx adjusted from https://github.com/jbrantly/yabble/blob/master/lib/yabble.js#L339\r\nexport var cjsRequireRegEx = /(?:^\\uFEFF?|[^$_a-zA-Z\\xA0-\\uFFFF.\"'])require\\s*\\(\\s*(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'|`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`)\\s*\\)/g\r\n","import { isWindows } from './common.js';\r\n\r\n/*\r\n * Source loading\r\n */\r\nfunction fetchFetch (url, authorization, integrity, asBuffer) {\r\n // fetch doesn't support file:/// urls\r\n if (url.substr(0, 8) === 'file:///') {\r\n if (hasXhr)\r\n return xhrFetch(url, authorization, integrity, asBuffer);\r\n else\r\n throw new Error('Unable to fetch file URLs in this environment.');\r\n }\r\n\r\n // percent encode just \"#\" for HTTP requests\r\n url = url.replace(/#/g, '%23');\r\n\r\n var opts = {\r\n // NB deprecate\r\n headers: { Accept: 'application/x-es-module, */*' }\r\n };\r\n\r\n if (integrity)\r\n opts.integrity = integrity;\r\n\r\n if (authorization) {\r\n if (typeof authorization == 'string')\r\n opts.headers['Authorization'] = authorization;\r\n opts.credentials = 'include';\r\n }\r\n\r\n return fetch(url, opts)\r\n .then(function(res) {\r\n if (res.ok)\r\n return asBuffer ? res.arrayBuffer() : res.text();\r\n else\r\n throw new Error('Fetch error: ' + res.status + ' ' + res.statusText);\r\n });\r\n}\r\n\r\nfunction xhrFetch (url, authorization, integrity, asBuffer) {\r\n return new Promise(function (resolve, reject) {\r\n // percent encode just \"#\" for HTTP requests\r\n url = url.replace(/#/g, '%23');\r\n\r\n var xhr = new XMLHttpRequest();\r\n if (asBuffer)\r\n xhr.responseType = 'arraybuffer';\r\n function load() {\r\n resolve(asBuffer ? xhr.response : xhr.responseText);\r\n }\r\n function error() {\r\n reject(new Error('XHR error: ' + (xhr.status ? ' (' + xhr.status + (xhr.statusText ? ' ' + xhr.statusText : '') + ')' : '') + ' loading ' + url));\r\n }\r\n\r\n xhr.onreadystatechange = function () {\r\n if (xhr.readyState === 4) {\r\n // in Chrome on file:/// URLs, status is 0\r\n if (xhr.status == 0) {\r\n if (xhr.response) {\r\n load();\r\n }\r\n else {\r\n // when responseText is empty, wait for load or error event\r\n // to inform if it is a 404 or empty file\r\n xhr.addEventListener('error', error);\r\n xhr.addEventListener('load', load);\r\n }\r\n }\r\n else if (xhr.status === 200) {\r\n load();\r\n }\r\n else {\r\n error();\r\n }\r\n }\r\n };\r\n xhr.open(\"GET\", url, true);\r\n\r\n if (xhr.setRequestHeader) {\r\n xhr.setRequestHeader('Accept', 'application/x-es-module, */*');\r\n // can set \"authorization: true\" to enable withCredentials only\r\n if (authorization) {\r\n if (typeof authorization == 'string')\r\n xhr.setRequestHeader('Authorization', authorization);\r\n xhr.withCredentials = true;\r\n }\r\n }\r\n\r\n xhr.send(null);\r\n });\r\n}\r\n\r\nvar fs;\r\nfunction nodeFetch (url, authorization, integrity, asBuffer) {\r\n if (url.substr(0, 8) != 'file:///') {\r\n if (hasFetch)\r\n return fetchFetch(url, authorization, integrity, asBuffer);\r\n else\r\n return Promise.reject(new Error('Unable to fetch \"' + url + '\". Only file URLs of the form file:/// supported running in Node without fetch.'));\r\n }\r\n \r\n fs = fs || require('fs');\r\n if (isWindows)\r\n url = url.replace(/\\//g, '\\\\').substr(8);\r\n else\r\n url = url.substr(7);\r\n\r\n return new Promise(function (resolve, reject) {\r\n fs.readFile(url, function(err, data) {\r\n if (err) {\r\n return reject(err);\r\n }\r\n else {\r\n if (asBuffer) {\r\n resolve(data);\r\n }\r\n else {\r\n // Strip Byte Order Mark out if it's the leading char\r\n var dataString = data + '';\r\n if (dataString[0] === '\\ufeff')\r\n dataString = dataString.substr(1);\r\n\r\n resolve(dataString);\r\n }\r\n }\r\n });\r\n });\r\n}\r\n\r\nfunction noFetch () {\r\n throw new Error('No fetch method is defined for this environment.');\r\n}\r\n\r\nvar fetchFunction;\r\n\r\nvar hasXhr = typeof XMLHttpRequest !== 'undefined';\r\nvar hasFetch = typeof fetch !== 'undefined';\r\n\r\nif (typeof self !== 'undefined' && typeof self.fetch !== 'undefined')\r\n fetchFunction = fetchFetch;\r\nelse if (hasXhr)\r\n fetchFunction = xhrFetch;\r\nelse if (typeof require !== 'undefined' && typeof process !== 'undefined')\r\n fetchFunction = nodeFetch;\r\nelse\r\n fetchFunction = noFetch;\r\n\r\nexport default fetchFunction;\r\n","import RegisterLoader from 'es-module-loader/core/register-loader.js';\r\nimport { getMapMatch, readMemberExpression, extendMeta, addToError, resolveIfNotPlain,\r\n baseURI, CONFIG, METADATA, applyPaths, resolvedPromise, getPackage } from './common.js';\r\nimport { setPkgConfig, createPackage } from './config.js';\r\nimport fetch from './fetch.js';\r\n\r\nexport function createMetadata () {\r\n return {\r\n pluginKey: undefined,\r\n pluginArgument: undefined,\r\n pluginModule: undefined,\r\n packageKey: undefined,\r\n packageConfig: undefined,\r\n load: undefined\r\n };\r\n}\r\n\r\nfunction getCoreParentMetadata (loader, config, parentKey) {\r\n var parentMetadata = createMetadata();\r\n\r\n if (parentKey) {\r\n // detect parent plugin\r\n // we just need pluginKey to be truthy for package configurations\r\n // so we duplicate it as pluginArgument - although not correct its not used\r\n var parentPluginIndex;\r\n if (config.pluginFirst) {\r\n if ((parentPluginIndex = parentKey.lastIndexOf('!')) !== -1)\r\n parentMetadata.pluginArgument = parentMetadata.pluginKey = parentKey.substr(0, parentPluginIndex);\r\n }\r\n else {\r\n if ((parentPluginIndex = parentKey.indexOf('!')) !== -1)\r\n parentMetadata.pluginArgument = parentMetadata.pluginKey = parentKey.substr(parentPluginIndex + 1);\r\n }\r\n }\r\n\r\n return parentMetadata;\r\n}\r\n\r\nfunction getParentMetadata (loader, config, parentKey) {\r\n var parentMetadata = createMetadata();\r\n\r\n if (parentKey) {\r\n // detect parent plugin\r\n // we just need pluginKey to be truthy for package configurations\r\n // so we duplicate it as pluginArgument - although not correct its not used\r\n var parentPluginIndex;\r\n if (config.pluginFirst) {\r\n if ((parentPluginIndex = parentKey.lastIndexOf('!')) !== -1)\r\n parentMetadata.pluginArgument = parentMetadata.pluginKey = parentKey.substr(0, parentPluginIndex);\r\n }\r\n else {\r\n if ((parentPluginIndex = parentKey.indexOf('!')) !== -1)\r\n parentMetadata.pluginArgument = parentMetadata.pluginKey = parentKey.substr(parentPluginIndex + 1);\r\n }\r\n\r\n // detect parent package\r\n parentMetadata.packageKey = getMapMatch(config.packages, parentKey);\r\n if (parentMetadata.packageKey)\r\n parentMetadata.packageConfig = config.packages[parentMetadata.packageKey];\r\n }\r\n\r\n return parentMetadata;\r\n}\r\n\r\nexport function normalize (key, parentKey) {\r\n var config = this[CONFIG];\r\n\r\n var metadata = createMetadata();\r\n var parentMetadata = getParentMetadata(this, config, parentKey);\r\n\r\n var loader = this;\r\n\r\n return Promise.resolve()\r\n\r\n // boolean conditional\r\n .then(function () {\r\n // first we normalize the conditional\r\n var booleanIndex = key.lastIndexOf('#?');\r\n\r\n if (booleanIndex === -1)\r\n return Promise.resolve(key);\r\n\r\n var conditionObj = parseCondition.call(loader, key.substr(booleanIndex + 2));\r\n\r\n // in builds, return normalized conditional\r\n /*if (this.builder)\r\n return this.resolve(conditionObj.module, parentKey)\r\n .then(function (conditionModule) {\r\n conditionObj.module = conditionModule;\r\n return key.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj);\r\n });*/\r\n\r\n return resolveCondition.call(loader, conditionObj, parentKey, true)\r\n .then(function (conditionValue) {\r\n return conditionValue ? key.substr(0, booleanIndex) : '@empty';\r\n });\r\n })\r\n\r\n // plugin\r\n .then(function (key) {\r\n var parsed = parsePlugin(config.pluginFirst, key);\r\n\r\n if (!parsed)\r\n return packageResolve.call(loader, config, key, parentMetadata && parentMetadata.pluginArgument || parentKey, metadata, parentMetadata, false);\r\n\r\n metadata.pluginKey = parsed.plugin;\r\n\r\n return Promise.all([\r\n packageResolve.call(loader, config, parsed.argument, parentMetadata && parentMetadata.pluginArgument || parentKey, metadata, parentMetadata, true),\r\n loader.resolve(parsed.plugin, parentKey)\r\n ])\r\n .then(function (normalized) {\r\n metadata.pluginArgument = normalized[0];\r\n metadata.pluginKey = normalized[1];\r\n\r\n // don't allow a plugin to load itself\r\n if (metadata.pluginArgument === metadata.pluginKey)\r\n throw new Error('Plugin ' + metadata.pluginArgument + ' cannot load itself, make sure it is excluded from any wildcard meta configuration via a custom loader: false rule.');\r\n\r\n return combinePluginParts(config.pluginFirst, normalized[0], normalized[1]);\r\n });\r\n })\r\n .then(function (normalized) {\r\n return interpolateConditional.call(loader, normalized, parentKey, parentMetadata);\r\n })\r\n .then(function (normalized) {\r\n setMeta.call(loader, config, normalized, metadata);\r\n\r\n if (metadata.pluginKey || !metadata.load.loader)\r\n return normalized;\r\n\r\n // loader by configuration\r\n // normalizes to parent to support package loaders\r\n return loader.resolve(metadata.load.loader, normalized)\r\n .then(function (pluginKey) {\r\n metadata.pluginKey = pluginKey;\r\n metadata.pluginArgument = normalized;\r\n return normalized;\r\n });\r\n })\r\n .then(function (normalized) {\r\n loader[METADATA][normalized] = metadata;\r\n return normalized;\r\n });\r\n}\r\n\r\n// normalization function used for registry keys\r\n// just does coreResolve without map\r\nexport function decanonicalize (config, key) {\r\n var parsed = parsePlugin(config.pluginFirst, key);\r\n\r\n // plugin\r\n if (parsed) {\r\n var pluginKey = decanonicalize.call(this, config, parsed.plugin);\r\n return combinePluginParts(config.pluginFirst, coreResolve.call(this, config, parsed.argument, undefined, false, false), pluginKey);\r\n }\r\n\r\n return coreResolve.call(this, config, key, undefined, false, false);\r\n}\r\n\r\nexport function normalizeSync (key, parentKey) {\r\n var config = this[CONFIG];\r\n\r\n // normalizeSync is metadataless, so create metadata\r\n var metadata = createMetadata();\r\n var parentMetadata = parentMetadata || getParentMetadata(this, config, parentKey);\r\n\r\n var parsed = parsePlugin(config.pluginFirst, key);\r\n\r\n // plugin\r\n if (parsed) {\r\n metadata.pluginKey = normalizeSync.call(this, parsed.plugin, parentKey);\r\n return combinePluginParts(config.pluginFirst,\r\n packageResolveSync.call(this, config, parsed.argument, parentMetadata.pluginArgument || parentKey, metadata, parentMetadata, !!metadata.pluginKey),\r\n metadata.pluginKey);\r\n }\r\n\r\n return packageResolveSync.call(this, config, key, parentMetadata.pluginArgument || parentKey, metadata, parentMetadata, !!metadata.pluginKey);\r\n}\r\n\r\nexport function coreResolve (config, key, parentKey, doMap, packageName) {\r\n var relativeResolved = resolveIfNotPlain(key, parentKey || baseURI);\r\n\r\n // standard URL resolution\r\n if (relativeResolved)\r\n return applyPaths(config.baseURL, config.paths, relativeResolved);\r\n\r\n // plain keys not starting with './', 'x://' and '/' go through custom resolution\r\n if (doMap) {\r\n var mapMatch = getMapMatch(config.map, key);\r\n\r\n if (mapMatch) {\r\n key = config.map[mapMatch] + key.substr(mapMatch.length);\r\n\r\n relativeResolved = resolveIfNotPlain(key, baseURI);\r\n if (relativeResolved)\r\n return applyPaths(config.baseURL, config.paths, relativeResolved);\r\n }\r\n }\r\n\r\n if (this.registry.has(key))\r\n return key;\r\n\r\n if (key.substr(0, 6) === '@node/')\r\n return key;\r\n\r\n var trailingSlash = packageName && key[key.length - 1] !== '/';\r\n var resolved = applyPaths(config.baseURL, config.paths, trailingSlash ? key + '/' : key);\r\n if (trailingSlash)\r\n return resolved.substr(0, resolved.length - 1);\r\n return resolved;\r\n}\r\n\r\nfunction packageResolveSync (config, key, parentKey, metadata, parentMetadata, skipExtensions) {\r\n // ignore . since internal maps handled by standard package resolution\r\n if (parentMetadata && parentMetadata.packageConfig && key[0] !== '.') {\r\n var parentMap = parentMetadata.packageConfig.map;\r\n var parentMapMatch = parentMap && getMapMatch(parentMap, key);\r\n\r\n if (parentMapMatch && typeof parentMap[parentMapMatch] === 'string') {\r\n var mapped = doMapSync(this, config, parentMetadata.packageConfig, parentMetadata.packageKey, parentMapMatch, key, metadata, skipExtensions);\r\n if (mapped)\r\n return mapped;\r\n }\r\n }\r\n\r\n var normalized = coreResolve.call(this, config, key, parentKey, true, true);\r\n\r\n var pkgConfigMatch = getPackageConfigMatch(config, normalized);\r\n metadata.packageKey = pkgConfigMatch && pkgConfigMatch.packageKey || getMapMatch(config.packages, normalized);\r\n\r\n if (!metadata.packageKey)\r\n return normalized;\r\n\r\n if (config.packageConfigKeys.indexOf(normalized) !== -1) {\r\n metadata.packageKey = undefined;\r\n return normalized;\r\n }\r\n\r\n metadata.packageConfig = config.packages[metadata.packageKey] || (config.packages[metadata.packageKey] = createPackage());\r\n\r\n var subPath = normalized.substr(metadata.packageKey.length + 1);\r\n\r\n return applyPackageConfigSync(this, config, metadata.packageConfig, metadata.packageKey, subPath, metadata, skipExtensions);\r\n}\r\n\r\nfunction packageResolve (config, key, parentKey, metadata, parentMetadata, skipExtensions) {\r\n var loader = this;\r\n\r\n return resolvedPromise\r\n .then(function () {\r\n // ignore . since internal maps handled by standard package resolution\r\n if (parentMetadata && parentMetadata.packageConfig && key.substr(0, 2) !== './') {\r\n var parentMap = parentMetadata.packageConfig.map;\r\n var parentMapMatch = parentMap && getMapMatch(parentMap, key);\r\n\r\n if (parentMapMatch)\r\n return doMap(loader, config, parentMetadata.packageConfig, parentMetadata.packageKey, parentMapMatch, key, metadata, skipExtensions);\r\n }\r\n\r\n return resolvedPromise;\r\n })\r\n .then(function (mapped) {\r\n if (mapped)\r\n return mapped;\r\n\r\n // apply map, core, paths, contextual package map\r\n var normalized = coreResolve.call(loader, config, key, parentKey, true, true);\r\n\r\n var pkgConfigMatch = getPackageConfigMatch(config, normalized);\r\n metadata.packageKey = pkgConfigMatch && pkgConfigMatch.packageKey || getMapMatch(config.packages, normalized);\r\n\r\n if (!metadata.packageKey)\r\n return Promise.resolve(normalized);\r\n\r\n if (config.packageConfigKeys.indexOf(normalized) !== -1) {\r\n metadata.packageKey = undefined;\r\n metadata.load = createMeta();\r\n metadata.load.format = 'json';\r\n // ensure no loader\r\n metadata.load.loader = '';\r\n return Promise.resolve(normalized);\r\n }\r\n\r\n metadata.packageConfig = config.packages[metadata.packageKey] || (config.packages[metadata.packageKey] = createPackage());\r\n\r\n // load configuration when it matches packageConfigPaths, not already configured, and not the config itself\r\n var loadConfig = pkgConfigMatch && !metadata.packageConfig.configured;\r\n\r\n return (loadConfig ? loadPackageConfigPath(loader, config, pkgConfigMatch.configPath, metadata) : resolvedPromise)\r\n .then(function () {\r\n var subPath = normalized.substr(metadata.packageKey.length + 1);\r\n\r\n return applyPackageConfig(loader, config, metadata.packageConfig, metadata.packageKey, subPath, metadata, skipExtensions);\r\n });\r\n });\r\n}\r\n\r\nfunction createMeta () {\r\n return {\r\n extension: '',\r\n deps: undefined,\r\n format: undefined,\r\n loader: undefined,\r\n scriptLoad: undefined,\r\n globals: undefined,\r\n nonce: undefined,\r\n integrity: undefined,\r\n sourceMap: undefined,\r\n exports: undefined,\r\n encapsulateGlobal: false,\r\n crossOrigin: undefined,\r\n cjsRequireDetection: true,\r\n cjsDeferDepsExecute: false,\r\n esModule: false\r\n };\r\n}\r\n\r\nfunction setMeta (config, key, metadata) {\r\n metadata.load = metadata.load || createMeta();\r\n\r\n // apply wildcard metas\r\n var bestDepth = 0;\r\n var wildcardIndex;\r\n for (var module in config.meta) {\r\n wildcardIndex = module.indexOf('*');\r\n if (wildcardIndex === -1)\r\n continue;\r\n if (module.substr(0, wildcardIndex) === key.substr(0, wildcardIndex)\r\n && module.substr(wildcardIndex + 1) === key.substr(key.length - module.length + wildcardIndex + 1)) {\r\n var depth = module.split('/').length;\r\n if (depth > bestDepth)\r\n bestDepth = depth;\r\n extendMeta(metadata.load, config.meta[module], bestDepth !== depth);\r\n }\r\n }\r\n\r\n // apply exact meta\r\n if (config.meta[key])\r\n extendMeta(metadata.load, config.meta[key], false);\r\n\r\n // apply package meta\r\n if (metadata.packageKey) {\r\n var subPath = key.substr(metadata.packageKey.length + 1);\r\n\r\n var meta = {};\r\n if (metadata.packageConfig.meta) {\r\n var bestDepth = 0;\r\n getMetaMatches(metadata.packageConfig.meta, subPath, function (metaPattern, matchMeta, matchDepth) {\r\n if (matchDepth > bestDepth)\r\n bestDepth = matchDepth;\r\n extendMeta(meta, matchMeta, matchDepth && bestDepth > matchDepth);\r\n });\r\n\r\n extendMeta(metadata.load, meta, false);\r\n }\r\n\r\n // format\r\n if (metadata.packageConfig.format && !metadata.pluginKey && !metadata.load.loader)\r\n metadata.load.format = metadata.load.format || metadata.packageConfig.format;\r\n }\r\n}\r\n\r\nfunction parsePlugin (pluginFirst, key) {\r\n var argumentKey;\r\n var pluginKey;\r\n\r\n var pluginIndex = pluginFirst ? key.indexOf('!') : key.lastIndexOf('!');\r\n\r\n if (pluginIndex === -1)\r\n return;\r\n\r\n if (pluginFirst) {\r\n argumentKey = key.substr(pluginIndex + 1);\r\n pluginKey = key.substr(0, pluginIndex);\r\n }\r\n else {\r\n argumentKey = key.substr(0, pluginIndex);\r\n pluginKey = key.substr(pluginIndex + 1) || argumentKey.substr(argumentKey.lastIndexOf('.') + 1);\r\n }\r\n\r\n return {\r\n argument: argumentKey,\r\n plugin: pluginKey\r\n };\r\n}\r\n\r\n// put key back together after parts have been normalized\r\nfunction combinePluginParts (pluginFirst, argumentKey, pluginKey) {\r\n if (pluginFirst)\r\n return pluginKey + '!' + argumentKey;\r\n else\r\n return argumentKey + '!' + pluginKey;\r\n}\r\n\r\n/*\r\n * Package Configuration Extension\r\n *\r\n * Example:\r\n *\r\n * SystemJS.packages = {\r\n * jquery: {\r\n * main: 'index.js', // when not set, package key is requested directly\r\n * format: 'amd',\r\n * defaultExtension: 'ts', // defaults to 'js', can be set to false\r\n * modules: {\r\n * '*.ts': {\r\n * loader: 'typescript'\r\n * },\r\n * 'vendor/sizzle.js': {\r\n * format: 'global'\r\n * }\r\n * },\r\n * map: {\r\n * // map internal require('sizzle') to local require('./vendor/sizzle')\r\n * sizzle: './vendor/sizzle.js',\r\n * // map any internal or external require of 'jquery/vendor/another' to 'another/index.js'\r\n * './vendor/another.js': './another/index.js',\r\n * // test.js / test -> lib/test.js\r\n * './test.js': './lib/test.js',\r\n *\r\n * // environment-specific map configurations\r\n * './index.js': {\r\n * '~browser': './index-node.js',\r\n * './custom-condition.js|~export': './index-custom.js'\r\n * }\r\n * },\r\n * // allows for setting package-prefixed depCache\r\n * // keys are normalized module keys relative to the package itself\r\n * depCache: {\r\n * // import 'package/index.js' loads in parallel package/lib/test.js,package/vendor/sizzle.js\r\n * './index.js': ['./test'],\r\n * './test.js': ['external-dep'],\r\n * 'external-dep/path.js': ['./another.js']\r\n * }\r\n * }\r\n * };\r\n *\r\n * Then:\r\n * import 'jquery' -> jquery/index.js\r\n * import 'jquery/submodule' -> jquery/submodule.js\r\n * import 'jquery/submodule.ts' -> jquery/submodule.ts loaded as typescript\r\n * import 'jquery/vendor/another' -> another/index.js\r\n *\r\n * Detailed Behaviours\r\n * - main can have a leading \"./\" can be added optionally\r\n * - map and defaultExtension are applied to the main\r\n * - defaultExtension adds the extension only if the exact extension is not present\r\n\r\n * - if a meta value is available for a module, map and defaultExtension are skipped\r\n * - like global map, package map also applies to subpaths (sizzle/x, ./vendor/another/sub)\r\n * - condition module map is '@env' module in package or '@system-env' globally\r\n * - map targets support conditional interpolation ('./x': './x.#{|env}.js')\r\n * - internal package map targets cannot use boolean conditionals\r\n *\r\n * Package Configuration Loading\r\n *\r\n * Not all packages may already have their configuration present in the System config\r\n * For these cases, a list of packageConfigPaths can be provided, which when matched against\r\n * a request, will first request a \".json\" file by the package key to derive the package\r\n * configuration from. This allows dynamic loading of non-predetermined code, a key use\r\n * case in SystemJS.\r\n *\r\n * Example:\r\n *\r\n * SystemJS.packageConfigPaths = ['packages/test/package.json', 'packages/*.json'];\r\n *\r\n * // will first request 'packages/new-package/package.json' for the package config\r\n * // before completing the package request to 'packages/new-package/path'\r\n * SystemJS.import('packages/new-package/path');\r\n *\r\n * // will first request 'packages/test/package.json' before the main\r\n * SystemJS.import('packages/test');\r\n *\r\n * When a package matches packageConfigPaths, it will always send a config request for\r\n * the package configuration.\r\n * The package key itself is taken to be the match up to and including the last wildcard\r\n * or trailing slash.\r\n * The most specific package config path will be used.\r\n * Any existing package configurations for the package will deeply merge with the\r\n * package config, with the existing package configurations taking preference.\r\n * To opt-out of the package configuration request for a package that matches\r\n * packageConfigPaths, use the { configured: true } package config option.\r\n *\r\n */\r\n\r\nfunction addDefaultExtension (config, pkg, pkgKey, subPath, skipExtensions) {\r\n // don't apply extensions to folders or if defaultExtension = false\r\n if (!subPath || !pkg.defaultExtension || subPath[subPath.length - 1] === '/' || skipExtensions)\r\n return subPath;\r\n\r\n var metaMatch = false;\r\n\r\n // exact meta or meta with any content after the last wildcard skips extension\r\n if (pkg.meta)\r\n getMetaMatches(pkg.meta, subPath, function (metaPattern, matchMeta, matchDepth) {\r\n if (matchDepth === 0 || metaPattern.lastIndexOf('*') !== metaPattern.length - 1)\r\n return metaMatch = true;\r\n });\r\n\r\n // exact global meta or meta with any content after the last wildcard skips extension\r\n if (!metaMatch && config.meta)\r\n getMetaMatches(config.meta, pkgKey + '/' + subPath, function (metaPattern, matchMeta, matchDepth) {\r\n if (matchDepth === 0 || metaPattern.lastIndexOf('*') !== metaPattern.length - 1)\r\n return metaMatch = true;\r\n });\r\n\r\n if (metaMatch)\r\n return subPath;\r\n\r\n // work out what the defaultExtension is and add if not there already\r\n var defaultExtension = '.' + pkg.defaultExtension;\r\n if (subPath.substr(subPath.length - defaultExtension.length) !== defaultExtension)\r\n return subPath + defaultExtension;\r\n else\r\n return subPath;\r\n}\r\n\r\nfunction applyPackageConfigSync (loader, config, pkg, pkgKey, subPath, metadata, skipExtensions) {\r\n // main\r\n if (!subPath) {\r\n if (pkg.main)\r\n subPath = pkg.main.substr(0, 2) === './' ? pkg.main.substr(2) : pkg.main;\r\n else\r\n // also no submap if key is package itself (import 'pkg' -> 'path/to/pkg.js')\r\n // NB can add a default package main convention here\r\n // if it becomes internal to the package then it would no longer be an exit path\r\n return pkgKey;\r\n }\r\n\r\n // map config checking without then with extensions\r\n if (pkg.map) {\r\n var mapPath = './' + subPath;\r\n\r\n var mapMatch = getMapMatch(pkg.map, mapPath);\r\n\r\n // we then check map with the default extension adding\r\n if (!mapMatch) {\r\n mapPath = './' + addDefaultExtension(config, pkg, pkgKey, subPath, skipExtensions);\r\n if (mapPath !== './' + subPath)\r\n mapMatch = getMapMatch(pkg.map, mapPath);\r\n }\r\n if (mapMatch) {\r\n var mapped = doMapSync(loader, config, pkg, pkgKey, mapMatch, mapPath, metadata, skipExtensions);\r\n if (mapped)\r\n return mapped;\r\n }\r\n }\r\n\r\n // normal package resolution\r\n return pkgKey + '/' + addDefaultExtension(config, pkg, pkgKey, subPath, skipExtensions);\r\n}\r\n\r\nfunction validMapping (mapMatch, mapped, path) {\r\n // allow internal ./x -> ./x/y or ./x/ -> ./x/y recursive maps\r\n // but only if the path is exactly ./x and not ./x/z\r\n if (mapped.substr(0, mapMatch.length) === mapMatch && path.length > mapMatch.length)\r\n return false;\r\n\r\n return true;\r\n}\r\n\r\nfunction doMapSync (loader, config, pkg, pkgKey, mapMatch, path, metadata, skipExtensions) {\r\n if (path[path.length - 1] === '/')\r\n path = path.substr(0, path.length - 1);\r\n var mapped = pkg.map[mapMatch];\r\n\r\n if (typeof mapped === 'object')\r\n throw new Error('Synchronous conditional normalization not supported sync normalizing ' + mapMatch + ' in ' + pkgKey);\r\n\r\n if (!validMapping(mapMatch, mapped, path) || typeof mapped !== 'string')\r\n return;\r\n\r\n return packageResolveSync.call(loader, config, mapped + path.substr(mapMatch.length), pkgKey + '/', metadata, metadata, skipExtensions);\r\n}\r\n\r\nfunction applyPackageConfig (loader, config, pkg, pkgKey, subPath, metadata, skipExtensions) {\r\n // main\r\n if (!subPath) {\r\n if (pkg.main)\r\n subPath = pkg.main.substr(0, 2) === './' ? pkg.main.substr(2) : pkg.main;\r\n // also no submap if key is package itself (import 'pkg' -> 'path/to/pkg.js')\r\n else\r\n // NB can add a default package main convention here\r\n // if it becomes internal to the package then it would no longer be an exit path\r\n return Promise.resolve(pkgKey);\r\n }\r\n\r\n // map config checking without then with extensions\r\n var mapPath, mapMatch;\r\n\r\n if (pkg.map) {\r\n mapPath = './' + subPath;\r\n mapMatch = getMapMatch(pkg.map, mapPath);\r\n\r\n // we then check map with the default extension adding\r\n if (!mapMatch) {\r\n mapPath = './' + addDefaultExtension(config, pkg, pkgKey, subPath, skipExtensions);\r\n if (mapPath !== './' + subPath)\r\n mapMatch = getMapMatch(pkg.map, mapPath);\r\n }\r\n }\r\n\r\n return (mapMatch ? doMap(loader, config, pkg, pkgKey, mapMatch, mapPath, metadata, skipExtensions) : resolvedPromise)\r\n .then(function (mapped) {\r\n if (mapped)\r\n return Promise.resolve(mapped);\r\n\r\n // normal package resolution / fallback resolution for no conditional match\r\n return Promise.resolve(pkgKey + '/' + addDefaultExtension(config, pkg, pkgKey, subPath, skipExtensions));\r\n });\r\n}\r\n\r\nfunction doMap (loader, config, pkg, pkgKey, mapMatch, path, metadata, skipExtensions) {\r\n if (path[path.length - 1] === '/')\r\n path = path.substr(0, path.length - 1);\r\n\r\n var mapped = pkg.map[mapMatch];\r\n\r\n if (typeof mapped === 'string') {\r\n if (!validMapping(mapMatch, mapped, path))\r\n return resolvedPromise;\r\n return packageResolve.call(loader, config, mapped + path.substr(mapMatch.length), pkgKey + '/', metadata, metadata, skipExtensions)\r\n .then(function (normalized) {\r\n return interpolateConditional.call(loader, normalized, pkgKey + '/', metadata);\r\n });\r\n }\r\n\r\n // we use a special conditional syntax to allow the builder to handle conditional branch points further\r\n /*if (loader.builder)\r\n return Promise.resolve(pkgKey + '/#:' + path);*/\r\n\r\n // we load all conditions upfront\r\n var conditionPromises = [];\r\n var conditions = [];\r\n for (var e in mapped) {\r\n var c = parseCondition(e);\r\n conditions.push({\r\n condition: c,\r\n map: mapped[e]\r\n });\r\n conditionPromises.push(RegisterLoader.prototype.import.call(loader, c.module, pkgKey));\r\n }\r\n\r\n // map object -> conditional map\r\n return Promise.all(conditionPromises)\r\n .then(function (conditionValues) {\r\n // first map condition to match is used\r\n for (var i = 0; i < conditions.length; i++) {\r\n var c = conditions[i].condition;\r\n var value = readMemberExpression(c.prop, '__useDefault' in conditionValues[i] ? conditionValues[i].__useDefault : conditionValues[i]);\r\n if (!c.negate && value || c.negate && !value)\r\n return conditions[i].map;\r\n }\r\n })\r\n .then(function (mapped) {\r\n if (mapped) {\r\n if (!validMapping(mapMatch, mapped, path))\r\n return resolvedPromise;\r\n return packageResolve.call(loader, config, mapped + path.substr(mapMatch.length), pkgKey + '/', metadata, metadata, skipExtensions)\r\n .then(function (normalized) {\r\n return interpolateConditional.call(loader, normalized, pkgKey + '/', metadata);\r\n });\r\n }\r\n\r\n // no environment match -> fallback to original subPath by returning undefined\r\n });\r\n}\r\n\r\n// check if the given normalized key matches a packageConfigPath\r\n// if so, loads the config\r\nvar packageConfigPaths = {};\r\n\r\n// data object for quick checks against package paths\r\nfunction createPkgConfigPathObj (path) {\r\n var lastWildcard = path.lastIndexOf('*');\r\n var length = Math.max(lastWildcard + 1, path.lastIndexOf('/'));\r\n return {\r\n length: length,\r\n regEx: new RegExp('^(' + path.substr(0, length).replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '[^\\\\/]+') + ')(\\\\/|$)'),\r\n wildcard: lastWildcard !== -1\r\n };\r\n}\r\n\r\n// most specific match wins\r\nfunction getPackageConfigMatch (config, normalized) {\r\n var pkgKey, exactMatch = false, configPath;\r\n for (var i = 0; i < config.packageConfigPaths.length; i++) {\r\n var packageConfigPath = config.packageConfigPaths[i];\r\n var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath));\r\n if (normalized.length < p.length)\r\n continue;\r\n var match = normalized.match(p.regEx);\r\n if (match && (!pkgKey || (!(exactMatch && p.wildcard) && pkgKey.length < match[1].length))) {\r\n pkgKey = match[1];\r\n exactMatch = !p.wildcard;\r\n configPath = pkgKey + packageConfigPath.substr(p.length);\r\n }\r\n }\r\n\r\n if (!pkgKey)\r\n return;\r\n\r\n return {\r\n packageKey: pkgKey,\r\n configPath: configPath\r\n };\r\n}\r\n\r\nfunction loadPackageConfigPath (loader, config, pkgConfigPath, metadata, normalized) {\r\n var configLoader = loader.pluginLoader || loader;\r\n\r\n // ensure we note this is a package config file path\r\n // it will then be skipped from getting other normalizations itself to ensure idempotency\r\n if (config.packageConfigKeys.indexOf(pkgConfigPath) === -1)\r\n config.packageConfigKeys.push(pkgConfigPath);\r\n\r\n return configLoader.import(pkgConfigPath)\r\n .then(function (pkgConfig) {\r\n setPkgConfig(metadata.packageConfig, pkgConfig, metadata.packageKey, true, config);\r\n metadata.packageConfig.configured = true;\r\n })\r\n .catch(function (err) {\r\n throw addToError(err, 'Unable to fetch package configuration file ' + pkgConfigPath);\r\n });\r\n}\r\n\r\nfunction getMetaMatches (pkgMeta, subPath, matchFn) {\r\n // wildcard meta\r\n var wildcardIndex;\r\n for (var module in pkgMeta) {\r\n // allow meta to start with ./ for flexibility\r\n var dotRel = module.substr(0, 2) === './' ? './' : '';\r\n if (dotRel)\r\n module = module.substr(2);\r\n\r\n wildcardIndex = module.indexOf('*');\r\n if (wildcardIndex === -1)\r\n continue;\r\n\r\n if (module.substr(0, wildcardIndex) === subPath.substr(0, wildcardIndex)\r\n && module.substr(wildcardIndex + 1) === subPath.substr(subPath.length - module.length + wildcardIndex + 1)) {\r\n // alow match function to return true for an exit path\r\n if (matchFn(module, pkgMeta[dotRel + module], module.split('/').length))\r\n return;\r\n }\r\n }\r\n // exact meta\r\n var exactMeta = pkgMeta[subPath] && Object.hasOwnProperty.call(pkgMeta, subPath) ? pkgMeta[subPath] : pkgMeta['./' + subPath];\r\n if (exactMeta)\r\n matchFn(exactMeta, exactMeta, 0);\r\n}\r\n\r\n\r\n/*\r\n * Conditions Extension\r\n *\r\n * Allows a condition module to alter the resolution of an import via syntax:\r\n *\r\n * import $ from 'jquery/#{browser}';\r\n *\r\n * Will first load the module 'browser' via `SystemJS.import('browser')` and\r\n * take the default export of that module.\r\n * If the default export is not a string, an error is thrown.\r\n *\r\n * We then substitute the string into the require to get the conditional resolution\r\n * enabling environment-specific variations like:\r\n *\r\n * import $ from 'jquery/ie'\r\n * import $ from 'jquery/firefox'\r\n * import $ from 'jquery/chrome'\r\n * import $ from 'jquery/safari'\r\n *\r\n * It can be useful for a condition module to define multiple conditions.\r\n * This can be done via the `|` modifier to specify an export member expression:\r\n *\r\n * import 'jquery/#{./browser.js|grade.version}'\r\n *\r\n * Where the `grade` export `version` member in the `browser.js` module is substituted.\r\n *\r\n *\r\n * Boolean Conditionals\r\n *\r\n * For polyfill modules, that are used as imports but have no module value,\r\n * a binary conditional allows a module not to be loaded at all if not needed:\r\n *\r\n * import 'es5-shim#?./conditions.js|needs-es5shim'\r\n *\r\n * These conditions can also be negated via:\r\n *\r\n * import 'es5-shim#?./conditions.js|~es6'\r\n *\r\n */\r\n\r\nvar sysConditions = ['browser', 'node', 'dev', 'build', 'production', 'default'];\r\n\r\nfunction parseCondition (condition) {\r\n var conditionExport, conditionModule, negation;\r\n\r\n var negation;\r\n var conditionExportIndex = condition.lastIndexOf('|');\r\n if (conditionExportIndex !== -1) {\r\n conditionExport = condition.substr(conditionExportIndex + 1);\r\n conditionModule = condition.substr(0, conditionExportIndex);\r\n\r\n if (conditionExport[0] === '~') {\r\n negation = true;\r\n conditionExport = conditionExport.substr(1);\r\n }\r\n }\r\n else {\r\n negation = condition[0] === '~';\r\n conditionExport = 'default';\r\n conditionModule = condition.substr(negation);\r\n if (sysConditions.indexOf(conditionModule) !== -1) {\r\n conditionExport = conditionModule;\r\n conditionModule = null;\r\n }\r\n }\r\n\r\n return {\r\n module: conditionModule || '@system-env',\r\n prop: conditionExport,\r\n negate: negation\r\n };\r\n}\r\n\r\nfunction resolveCondition (conditionObj, parentKey, bool) {\r\n // import without __useDefault handling here\r\n return RegisterLoader.prototype.import.call(this, conditionObj.module, parentKey)\r\n .then(function (condition) {\r\n var m = readMemberExpression(conditionObj.prop, condition);\r\n\r\n if (bool && typeof m !== 'boolean')\r\n throw new TypeError('Condition did not resolve to a boolean.');\r\n\r\n return conditionObj.negate ? !m : m;\r\n });\r\n}\r\n\r\nvar interpolationRegEx = /#\\{[^\\}]+\\}/;\r\nfunction interpolateConditional (key, parentKey, parentMetadata) {\r\n // first we normalize the conditional\r\n var conditionalMatch = key.match(interpolationRegEx);\r\n\r\n if (!conditionalMatch)\r\n return Promise.resolve(key);\r\n\r\n var conditionObj = parseCondition.call(this, conditionalMatch[0].substr(2, conditionalMatch[0].length - 3));\r\n\r\n // in builds, return normalized conditional\r\n /*if (this.builder)\r\n return this.normalize(conditionObj.module, parentKey, createMetadata(), parentMetadata)\r\n .then(function (conditionModule) {\r\n conditionObj.module = conditionModule;\r\n return key.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}');\r\n });*/\r\n\r\n return resolveCondition.call(this, conditionObj, parentKey, false)\r\n .then(function (conditionValue) {\r\n if (typeof conditionValue !== 'string')\r\n throw new TypeError('The condition value for ' + key + ' doesn\\'t resolve to a string.');\r\n\r\n if (conditionValue.indexOf('/') !== -1)\r\n throw new TypeError('Unabled to interpolate conditional ' + key + (parentKey ? ' in ' + parentKey : '') + '\\n\\tThe condition value ' + conditionValue + ' cannot contain a \"/\" separator.');\r\n\r\n return key.replace(interpolationRegEx, conditionValue);\r\n });\r\n}\r\n","import { envModule, setProduction, configNames } from './systemjs-loader.js';\r\nimport { extend, prepend, warn, resolveIfNotPlain, baseURI, CONFIG } from './common.js';\r\nimport { coreResolve } from './resolve.js';\r\n\r\n/*\r\n Extend config merging one deep only\r\n\r\n loader.config({\r\n some: 'random',\r\n config: 'here',\r\n deep: {\r\n config: { too: 'too' }\r\n }\r\n });\r\n\r\n <=>\r\n\r\n loader.some = 'random';\r\n loader.config = 'here'\r\n loader.deep = loader.deep || {};\r\n loader.deep.config = { too: 'too' };\r\n\r\n\r\n Normalizes meta and package configs allowing for:\r\n\r\n SystemJS.config({\r\n meta: {\r\n './index.js': {}\r\n }\r\n });\r\n\r\n To become\r\n\r\n SystemJS.meta['https://thissite.com/index.js'] = {};\r\n\r\n For easy normalization canonicalization with latest URL support.\r\n\r\n*/\r\nvar envConfigNames = ['browserConfig', 'nodeConfig', 'devConfig', 'buildConfig', 'productionConfig'];\r\nfunction envSet(loader, cfg, envCallback) {\r\n for (var i = 0; i < envConfigNames.length; i++) {\r\n var envConfig = envConfigNames[i];\r\n if (cfg[envConfig] && envModule[envConfig.substr(0, envConfig.length - 6)])\r\n envCallback(cfg[envConfig]);\r\n }\r\n}\r\n\r\nfunction cloneObj (obj, maxDepth) {\r\n var clone = {};\r\n for (var p in obj) {\r\n var prop = obj[p];\r\n if (maxDepth > 1) {\r\n if (prop instanceof Array)\r\n clone[p] = [].concat(prop);\r\n else if (typeof prop === 'object')\r\n clone[p] = cloneObj(prop, maxDepth - 1);\r\n else if (p !== 'packageConfig')\r\n clone[p] = prop;\r\n }\r\n else {\r\n clone[p] = prop;\r\n }\r\n }\r\n return clone;\r\n}\r\n\r\nexport function getConfigItem (config, p) {\r\n var cfgItem = config[p];\r\n\r\n // getConfig must return an unmodifiable clone of the configuration\r\n if (cfgItem instanceof Array)\r\n return config[p].concat([]);\r\n else if (typeof cfgItem === 'object')\r\n return cloneObj(cfgItem, 3)\r\n else\r\n return config[p];\r\n}\r\n\r\nexport function getConfig (configName) {\r\n if (configName) {\r\n if (configNames.indexOf(configName) !== -1)\r\n return getConfigItem(this[CONFIG], configName);\r\n throw new Error('\"' + configName + '\" is not a valid configuration name. Must be one of ' + configNames.join(', ') + '.');\r\n }\r\n\r\n var cfg = {};\r\n for (var i = 0; i < configNames.length; i++) {\r\n var p = configNames[i];\r\n var configItem = getConfigItem(this[CONFIG], p);\r\n if (configItem !== undefined)\r\n cfg[p] = configItem;\r\n }\r\n return cfg;\r\n}\r\n\r\nexport function setConfig (cfg, isEnvConfig) {\r\n var loader = this;\r\n var config = this[CONFIG];\r\n\r\n if ('warnings' in cfg)\r\n config.warnings = cfg.warnings;\r\n\r\n if ('wasm' in cfg)\r\n config.wasm = typeof WebAssembly !== 'undefined' && cfg.wasm;\r\n\r\n if ('production' in cfg || 'build' in cfg)\r\n setProduction.call(loader, !!cfg.production, !!(cfg.build || envModule && envModule.build));\r\n\r\n if (!isEnvConfig) {\r\n // if using nodeConfig / browserConfig / productionConfig, take baseURL from there\r\n // these exceptions will be unnecessary when we can properly implement config queuings\r\n var baseURL;\r\n envSet(loader, cfg, function(cfg) {\r\n baseURL = baseURL || cfg.baseURL;\r\n });\r\n baseURL = baseURL || cfg.baseURL;\r\n\r\n // always configure baseURL first\r\n if (baseURL) {\r\n config.baseURL = resolveIfNotPlain(baseURL, baseURI) || resolveIfNotPlain('./' + baseURL, baseURI);\r\n if (config.baseURL[config.baseURL.length - 1] !== '/')\r\n config.baseURL += '/';\r\n }\r\n\r\n if (cfg.paths)\r\n extend(config.paths, cfg.paths);\r\n\r\n envSet(loader, cfg, function(cfg) {\r\n if (cfg.paths)\r\n extend(config.paths, cfg.paths);\r\n });\r\n\r\n for (var p in config.paths) {\r\n if (config.paths[p].indexOf('*') === -1)\r\n continue;\r\n warn.call(config, 'Path config ' + p + ' -> ' + config.paths[p] + ' is no longer supported as wildcards are deprecated.');\r\n delete config.paths[p];\r\n }\r\n }\r\n\r\n if (cfg.defaultJSExtensions)\r\n warn.call(config, 'The defaultJSExtensions configuration option is deprecated.\\n Use packages defaultExtension instead.', true);\r\n\r\n if (typeof cfg.pluginFirst === 'boolean')\r\n config.pluginFirst = cfg.pluginFirst;\r\n\r\n if (cfg.map) {\r\n for (var p in cfg.map) {\r\n var v = cfg.map[p];\r\n\r\n if (typeof v === 'string') {\r\n var mapped = coreResolve.call(loader, config, v, undefined, false, false);\r\n if (mapped[mapped.length -1] === '/' && p[p.length - 1] !== ':' && p[p.length - 1] !== '/')\r\n mapped = mapped.substr(0, mapped.length - 1);\r\n config.map[p] = mapped;\r\n }\r\n\r\n // object map\r\n else {\r\n var pkgName = coreResolve.call(loader, config, p[p.length - 1] !== '/' ? p + '/' : p, undefined, true, true);\r\n pkgName = pkgName.substr(0, pkgName.length - 1);\r\n\r\n var pkg = config.packages[pkgName];\r\n if (!pkg) {\r\n pkg = config.packages[pkgName] = createPackage();\r\n // use '' instead of false to keep type consistent\r\n pkg.defaultExtension = '';\r\n }\r\n setPkgConfig(pkg, { map: v }, pkgName, false, config);\r\n }\r\n }\r\n }\r\n\r\n if (cfg.packageConfigPaths) {\r\n var packageConfigPaths = [];\r\n for (var i = 0; i < cfg.packageConfigPaths.length; i++) {\r\n var path = cfg.packageConfigPaths[i];\r\n var packageLength = Math.max(path.lastIndexOf('*') + 1, path.lastIndexOf('/'));\r\n var normalized = coreResolve.call(loader, config, path.substr(0, packageLength), undefined, false, false);\r\n packageConfigPaths[i] = normalized + path.substr(packageLength);\r\n }\r\n config.packageConfigPaths = packageConfigPaths;\r\n }\r\n\r\n if (cfg.bundles) {\r\n for (var p in cfg.bundles) {\r\n var bundle = [];\r\n for (var i = 0; i < cfg.bundles[p].length; i++)\r\n bundle.push(loader.normalizeSync(cfg.bundles[p][i]));\r\n config.bundles[p] = bundle;\r\n }\r\n }\r\n\r\n if (cfg.packages) {\r\n for (var p in cfg.packages) {\r\n if (p.match(/^([^\\/]+:)?\\/\\/$/))\r\n throw new TypeError('\"' + p + '\" is not a valid package name.');\r\n\r\n var pkgName = coreResolve.call(loader, config, p[p.length - 1] !== '/' ? p + '/' : p, undefined, true, true);\r\n pkgName = pkgName.substr(0, pkgName.length - 1);\r\n\r\n setPkgConfig(config.packages[pkgName] = config.packages[pkgName] || createPackage(), cfg.packages[p], pkgName, false, config);\r\n }\r\n }\r\n\r\n if (cfg.depCache) {\r\n for (var p in cfg.depCache)\r\n config.depCache[loader.normalizeSync(p)] = [].concat(cfg.depCache[p]);\r\n }\r\n\r\n if (cfg.meta) {\r\n for (var p in cfg.meta) {\r\n // base wildcard stays base\r\n if (p[0] === '*') {\r\n extend(config.meta[p] = config.meta[p] || {}, cfg.meta[p]);\r\n }\r\n else {\r\n var resolved = coreResolve.call(loader, config, p, undefined, true, true);\r\n extend(config.meta[resolved] = config.meta[resolved] || {}, cfg.meta[p]);\r\n }\r\n }\r\n }\r\n\r\n if ('transpiler' in cfg)\r\n config.transpiler = cfg.transpiler;\r\n\r\n\r\n // copy any remaining non-standard configuration properties\r\n for (var c in cfg) {\r\n if (configNames.indexOf(c) !== -1)\r\n continue;\r\n if (envConfigNames.indexOf(c) !== -1)\r\n continue;\r\n\r\n // warn.call(config, 'Setting custom config option `System.config({ ' + c + ': ... })` is deprecated. Avoid custom config options or set SystemJS.' + c + ' = ... directly.');\r\n loader[c] = cfg[c];\r\n }\r\n\r\n envSet(loader, cfg, function(cfg) {\r\n loader.config(cfg, true);\r\n });\r\n}\r\n\r\nexport function createPackage () {\r\n return {\r\n defaultExtension: undefined,\r\n main: undefined,\r\n format: undefined,\r\n meta: undefined,\r\n map: undefined,\r\n packageConfig: undefined,\r\n configured: false\r\n };\r\n}\r\n\r\n// deeply-merge (to first level) config with any existing package config\r\nexport function setPkgConfig (pkg, cfg, pkgName, prependConfig, config) {\r\n for (var prop in cfg) {\r\n if (prop === 'main' || prop === 'format' || prop === 'defaultExtension' || prop === 'configured') {\r\n if (!prependConfig || pkg[prop] === undefined)\r\n pkg[prop] = cfg[prop];\r\n }\r\n else if (prop === 'map') {\r\n (prependConfig ? prepend : extend)(pkg.map = pkg.map || {}, cfg.map);\r\n }\r\n else if (prop === 'meta') {\r\n (prependConfig ? prepend : extend)(pkg.meta = pkg.meta || {}, cfg.meta);\r\n }\r\n else if (Object.hasOwnProperty.call(cfg, prop)) {\r\n warn.call(config, '\"' + prop + '\" is not a valid package configuration option in package ' + pkgName);\r\n }\r\n }\r\n\r\n // default defaultExtension for packages only\r\n if (pkg.defaultExtension === undefined)\r\n pkg.defaultExtension = 'js';\r\n\r\n if (pkg.main === undefined && pkg.map && pkg.map['.']) {\r\n pkg.main = pkg.map['.'];\r\n delete pkg.map['.'];\r\n }\r\n // main object becomes main map\r\n else if (typeof pkg.main === 'object') {\r\n pkg.map = pkg.map || {};\r\n pkg.map['./@main'] = pkg.main;\r\n pkg.main['default'] = pkg.main['default'] || './';\r\n pkg.main = '@main';\r\n }\r\n\r\n return pkg;\r\n}\r\n","import { isBrowser, global } from './common.js';\r\n\r\nvar hasBuffer = typeof Buffer !== 'undefined';\r\ntry {\r\n if (hasBuffer && new Buffer('a').toString('base64') !== 'YQ==')\r\n hasBuffer = false;\r\n}\r\ncatch (e) {\r\n hasBuffer = false;\r\n}\r\n\r\nvar sourceMapPrefix = '\\n//# sourceMapping' + 'URL=data:application/json;base64,';\r\nfunction inlineSourceMap (sourceMapString) {\r\n if (hasBuffer)\r\n return sourceMapPrefix + new Buffer(sourceMapString).toString('base64');\r\n else if (typeof btoa !== 'undefined')\r\n return sourceMapPrefix + btoa(unescape(encodeURIComponent(sourceMapString)));\r\n else\r\n return '';\r\n}\r\n\r\nfunction getSource(source, sourceMap, address, wrap) {\r\n var lastLineIndex = source.lastIndexOf('\\n');\r\n\r\n if (sourceMap) {\r\n if (typeof sourceMap != 'object')\r\n throw new TypeError('load.metadata.sourceMap must be set to an object.');\r\n\r\n sourceMap = JSON.stringify(sourceMap);\r\n }\r\n\r\n return (wrap ? '(function(System, SystemJS) {' : '') + source + (wrap ? '\\n})(System, System);' : '')\r\n // adds the sourceURL comment if not already present\r\n + (source.substr(lastLineIndex, 15) != '\\n//# sourceURL='\r\n ? '\\n//# sourceURL=' + address + (sourceMap ? '!transpiled' : '') : '')\r\n // add sourceMappingURL if load.metadata.sourceMap is set\r\n + (sourceMap && inlineSourceMap(sourceMap) || '');\r\n}\r\n\r\n// script execution via injecting a script tag into the page\r\n// this allows CSP nonce to be set for CSP environments\r\nvar head;\r\nfunction scriptExec(loader, source, sourceMap, address, nonce) {\r\n if (!head)\r\n head = document.head || document.body || document.documentElement;\r\n\r\n var script = document.createElement('script');\r\n script.text = getSource(source, sourceMap, address, false);\r\n var onerror = window.onerror;\r\n var e;\r\n window.onerror = function(_e) {\r\n e = addToError(_e, 'Evaluating ' + address);\r\n if (onerror)\r\n onerror.apply(this, arguments);\r\n }\r\n preExec(loader);\r\n\r\n if (nonce)\r\n script.setAttribute('nonce', nonce);\r\n\r\n head.appendChild(script);\r\n head.removeChild(script);\r\n postExec();\r\n window.onerror = onerror;\r\n if (e)\r\n return e;\r\n}\r\n\r\nvar vm;\r\nvar useVm;\r\n\r\nvar curSystem;\r\n\r\nvar callCounter = 0;\r\nfunction preExec (loader) {\r\n if (callCounter++ == 0)\r\n curSystem = global.System;\r\n global.System = global.SystemJS = loader;\r\n}\r\nfunction postExec () {\r\n if (--callCounter == 0)\r\n global.System = global.SystemJS = curSystem;\r\n}\r\n\r\nvar supportsScriptExec = false;\r\nif (isBrowser && typeof document != 'undefined' && document.getElementsByTagName) {\r\n if (!(window.chrome && window.chrome.extension || navigator.userAgent.match(/^Node\\.js/)))\r\n supportsScriptExec = true;\r\n}\r\n\r\nexport function evaluate (loader, source, sourceMap, address, integrity, nonce, noWrap) {\r\n if (!source)\r\n return;\r\n if (nonce && supportsScriptExec)\r\n return scriptExec(loader, source, sourceMap, address, nonce);\r\n try {\r\n preExec(loader);\r\n // global scoped eval for node (avoids require scope leak)\r\n if (!vm && loader._nodeRequire) {\r\n vm = loader._nodeRequire('vm');\r\n useVm = vm.runInThisContext(\"typeof System !== 'undefined' && System\") === loader;\r\n }\r\n if (useVm)\r\n vm.runInThisContext(getSource(source, sourceMap, address, !noWrap), { filename: address + (sourceMap ? '!transpiled' : '') });\r\n else\r\n (0, eval)(getSource(source, sourceMap, address, !noWrap));\r\n postExec();\r\n }\r\n catch (e) {\r\n postExec();\r\n return e;\r\n }\r\n}\r\n","\r\nimport { isWindows, global, readMemberExpression, cjsRequireRegEx, noop } from './common.js';\r\n\r\nexport function setHelpers (loader) {\r\n loader.set('@@cjs-helpers', loader.newModule({\r\n requireResolve: requireResolve.bind(loader),\r\n getPathVars: getPathVars\r\n }));\r\n\r\n loader.set('@@global-helpers', loader.newModule({\r\n prepareGlobal: prepareGlobal\r\n }));\r\n}\r\n\r\nexport function setAmdHelper (loader) {\r\n\r\n /*\r\n AMD-compatible require\r\n To copy RequireJS, set window.require = window.requirejs = loader.amdRequire\r\n */\r\n function require (names, callback, errback, referer) {\r\n // in amd, first arg can be a config object... we just ignore\r\n if (typeof names === 'object' && !(names instanceof Array))\r\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\r\n\r\n // amd require\r\n if (typeof names === 'string' && typeof callback === 'function')\r\n names = [names];\r\n if (names instanceof Array) {\r\n var dynamicRequires = [];\r\n for (var i = 0; i < names.length; i++)\r\n dynamicRequires.push(loader.import(names[i], referer));\r\n Promise.all(dynamicRequires).then(function (modules) {\r\n if (callback)\r\n callback.apply(null, modules);\r\n }, errback);\r\n }\r\n\r\n // commonjs require\r\n else if (typeof names === 'string') {\r\n var normalized = loader.decanonicalize(names, referer);\r\n var module = loader.get(normalized);\r\n if (!module)\r\n throw new Error('Module not already loaded loading \"' + names + '\" as ' + normalized + (referer ? ' from \"' + referer + '\".' : '.'));\r\n return '__useDefault' in module ? module.__useDefault : module;\r\n }\r\n\r\n else\r\n throw new TypeError('Invalid require');\r\n }\r\n\r\n function define (name, deps, factory) {\r\n if (typeof name !== 'string') {\r\n factory = deps;\r\n deps = name;\r\n name = null;\r\n }\r\n\r\n if (!(deps instanceof Array)) {\r\n factory = deps;\r\n deps = ['require', 'exports', 'module'].splice(0, factory.length);\r\n }\r\n\r\n if (typeof factory !== 'function')\r\n factory = (function (factory) {\r\n return function() { return factory; }\r\n })(factory);\r\n\r\n if (!name) {\r\n if (curMetaDeps) {\r\n deps = deps.concat(curMetaDeps);\r\n curMetaDeps = undefined;\r\n }\r\n }\r\n\r\n // remove system dependencies\r\n var requireIndex, exportsIndex, moduleIndex;\r\n\r\n if ((requireIndex = deps.indexOf('require')) !== -1) {\r\n\r\n deps.splice(requireIndex, 1);\r\n\r\n // only trace cjs requires for non-named\r\n // named defines assume the trace has already been done\r\n if (!name)\r\n deps = deps.concat(amdGetCJSDeps(factory.toString(), requireIndex));\r\n }\r\n\r\n if ((exportsIndex = deps.indexOf('exports')) !== -1)\r\n deps.splice(exportsIndex, 1);\r\n\r\n if ((moduleIndex = deps.indexOf('module')) !== -1)\r\n deps.splice(moduleIndex, 1);\r\n\r\n function execute (req, exports, module) {\r\n var depValues = [];\r\n for (var i = 0; i < deps.length; i++)\r\n depValues.push(req(deps[i]));\r\n\r\n module.uri = module.id;\r\n\r\n module.config = noop;\r\n\r\n // add back in system dependencies\r\n if (moduleIndex !== -1)\r\n depValues.splice(moduleIndex, 0, module);\r\n\r\n if (exportsIndex !== -1)\r\n depValues.splice(exportsIndex, 0, exports);\r\n\r\n if (requireIndex !== -1) {\r\n var contextualRequire = function (names, callback, errback) {\r\n if (typeof names === 'string' && typeof callback !== 'function')\r\n return req(names);\r\n return require.call(loader, names, callback, errback, module.id);\r\n };\r\n contextualRequire.toUrl = function (name) {\r\n return loader.normalizeSync(name, module.id);\r\n };\r\n depValues.splice(requireIndex, 0, contextualRequire);\r\n }\r\n\r\n // set global require to AMD require\r\n var curRequire = global.require;\r\n global.require = require;\r\n\r\n var output = factory.apply(exportsIndex === -1 ? global : exports, depValues);\r\n\r\n global.require = curRequire;\r\n\r\n if (typeof output !== 'undefined')\r\n module.exports = output;\r\n }\r\n\r\n // anonymous define\r\n if (!name) {\r\n loader.registerDynamic(deps, false, curEsModule ? wrapEsModuleExecute(execute) : execute);\r\n }\r\n else {\r\n loader.registerDynamic(name, deps, false, execute);\r\n\r\n // if we don't have any other defines,\r\n // then let this be an anonymous define\r\n // this is just to support single modules of the form:\r\n // define('jquery')\r\n // still loading anonymously\r\n // because it is done widely enough to be useful\r\n // as soon as there is more than one define, this gets removed though\r\n if (lastNamedDefine) {\r\n lastNamedDefine = undefined;\r\n multipleNamedDefines = true;\r\n }\r\n else if (!multipleNamedDefines) {\r\n lastNamedDefine = [deps, execute];\r\n }\r\n }\r\n }\r\n define.amd = {};\r\n\r\n loader.amdDefine = define;\r\n loader.amdRequire = require;\r\n}\r\n\r\n// CJS\r\nvar windowOrigin;\r\nif (typeof window !== 'undefined' && typeof document !== 'undefined' && window.location)\r\n windowOrigin = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');\r\n\r\nfunction stripOrigin(path) {\r\n if (path.substr(0, 8) === 'file:///')\r\n return path.substr(7 + !!isWindows);\r\n\r\n if (windowOrigin && path.substr(0, windowOrigin.length) === windowOrigin)\r\n return path.substr(windowOrigin.length);\r\n\r\n return path;\r\n}\r\n\r\nexport function requireResolve (request, parentId) {\r\n return stripOrigin(this.normalizeSync(request, parentId));\r\n}\r\n\r\nexport function getPathVars (moduleId) {\r\n // remove any plugin syntax\r\n var pluginIndex = moduleId.lastIndexOf('!');\r\n var filename;\r\n if (pluginIndex !== -1)\r\n filename = moduleId.substr(0, pluginIndex);\r\n else\r\n filename = moduleId;\r\n\r\n var dirname = filename.split('/');\r\n dirname.pop();\r\n dirname = dirname.join('/');\r\n\r\n return {\r\n filename: stripOrigin(filename),\r\n dirname: stripOrigin(dirname)\r\n };\r\n}\r\n\r\nvar commentRegEx = /(^|[^\\\\])(\\/\\*([\\s\\S]*?)\\*\\/|([^:]|^)\\/\\/(.*)$)/mg;\r\nvar stringRegEx = /(\"[^\"\\\\\\n\\r]*(\\\\.[^\"\\\\\\n\\r]*)*\"|'[^'\\\\\\n\\r]*(\\\\.[^'\\\\\\n\\r]*)*')/g;\r\n\r\n// used to support leading #!/usr/bin/env in scripts as supported in Node\r\nvar hashBangRegEx = /^\\#\\!.*/;\r\n\r\n// extract CJS dependencies from source text via regex static analysis\r\n// read require('x') statements not in comments or strings\r\nexport function getCJSDeps (source) {\r\n cjsRequireRegEx.lastIndex = commentRegEx.lastIndex = stringRegEx.lastIndex = 0;\r\n\r\n var deps = [];\r\n\r\n var match;\r\n\r\n // track string and comment locations for unminified source\r\n var stringLocations = [], commentLocations = [];\r\n\r\n function inLocation (locations, match) {\r\n for (var i = 0; i < locations.length; i++)\r\n if (locations[i][0] < match.index && locations[i][1] > match.index)\r\n return true;\r\n return false;\r\n }\r\n\r\n if (source.length / source.split('\\n').length < 200) {\r\n while (match = stringRegEx.exec(source))\r\n stringLocations.push([match.index, match.index + match[0].length]);\r\n\r\n // TODO: track template literals here before comments\r\n\r\n while (match = commentRegEx.exec(source)) {\r\n // only track comments not starting in strings\r\n if (!inLocation(stringLocations, match))\r\n commentLocations.push([match.index + match[1].length, match.index + match[0].length - 1]);\r\n }\r\n }\r\n\r\n while (match = cjsRequireRegEx.exec(source)) {\r\n // ensure we're not within a string or comment location\r\n if (!inLocation(stringLocations, match) && !inLocation(commentLocations, match)) {\r\n var dep = match[1].substr(1, match[1].length - 2);\r\n // skip cases like require('\" + file + \"')\r\n if (dep.match(/\"|'/))\r\n continue;\r\n deps.push(dep);\r\n }\r\n }\r\n\r\n return deps;\r\n}\r\n\r\n// Global\r\n// bare minimum ignores\r\nvar ignoredGlobalProps = ['_g', 'sessionStorage', 'localStorage', 'clipboardData', 'frames', 'frameElement', 'external',\r\n 'mozAnimationStartTime', 'mozPaintCount', 'webkitStorageInfo', 'webkitIndexedDB', 'mozInnerScreenY', 'mozInnerScreenX'];\r\n\r\nvar globalSnapshot;\r\nexport function globalIterator (globalName) {\r\n if (ignoredGlobalProps.indexOf(globalName) !== -1)\r\n return;\r\n try {\r\n var value = global[globalName];\r\n }\r\n catch (e) {\r\n ignoredGlobalProps.push(globalName);\r\n }\r\n this(globalName, value);\r\n}\r\n\r\nexport function getGlobalValue (exports) {\r\n if (typeof exports === 'string')\r\n return readMemberExpression(exports, global);\r\n\r\n if (!(exports instanceof Array))\r\n throw new Error('Global exports must be a string or array.');\r\n\r\n var globalValue = {};\r\n for (var i = 0; i < exports.length; i++)\r\n globalValue[exports[i].split('.').pop()] = readMemberExpression(exports[i], global);\r\n return globalValue;\r\n}\r\n\r\nexport function prepareGlobal (moduleName, exports, globals, encapsulate) {\r\n // disable module detection\r\n var curDefine = global.define;\r\n\r\n global.define = undefined;\r\n\r\n // set globals\r\n var oldGlobals;\r\n if (globals) {\r\n oldGlobals = {};\r\n for (var g in globals) {\r\n oldGlobals[g] = global[g];\r\n global[g] = globals[g];\r\n }\r\n }\r\n\r\n // store a complete copy of the global object in order to detect changes\r\n if (!exports) {\r\n globalSnapshot = {};\r\n\r\n Object.keys(global).forEach(globalIterator, function (name, value) {\r\n globalSnapshot[name] = value;\r\n });\r\n }\r\n\r\n // return function to retrieve global\r\n return function () {\r\n var globalValue = exports ? getGlobalValue(exports) : {};\r\n\r\n var singleGlobal;\r\n var multipleExports = !!exports;\r\n\r\n if (!exports || encapsulate)\r\n Object.keys(global).forEach(globalIterator, function (name, value) {\r\n if (globalSnapshot[name] === value)\r\n return;\r\n if (value === undefined)\r\n return;\r\n\r\n // allow global encapsulation where globals are removed\r\n if (encapsulate)\r\n global[name] = undefined;\r\n\r\n if (!exports) {\r\n globalValue[name] = value;\r\n\r\n if (singleGlobal !== undefined) {\r\n if (!multipleExports && singleGlobal !== value)\r\n multipleExports = true;\r\n }\r\n else {\r\n singleGlobal = value;\r\n }\r\n }\r\n });\r\n\r\n globalValue = multipleExports ? globalValue : singleGlobal;\r\n\r\n // revert globals\r\n if (oldGlobals) {\r\n for (var g in oldGlobals)\r\n global[g] = oldGlobals[g];\r\n }\r\n global.define = curDefine;\r\n\r\n return globalValue;\r\n };\r\n}\r\n\r\n// AMD\r\nvar cjsRequirePre = \"(?:^|[^$_a-zA-Z\\\\xA0-\\\\uFFFF.])\";\r\nvar cjsRequirePost = \"\\\\s*\\\\(\\\\s*(\\\"([^\\\"]+)\\\"|'([^']+)')\\\\s*\\\\)\";\r\nvar fnBracketRegEx = /\\(([^\\)]*)\\)/;\r\nvar wsRegEx = /^\\s+|\\s+$/g;\r\n\r\nvar requireRegExs = {};\r\n\r\nfunction amdGetCJSDeps(source, requireIndex) {\r\n\r\n // remove comments\r\n source = source.replace(commentRegEx, '');\r\n\r\n // determine the require alias\r\n var params = source.match(fnBracketRegEx);\r\n var requireAlias = (params[1].split(',')[requireIndex] || 'require').replace(wsRegEx, '');\r\n\r\n // find or generate the regex for this requireAlias\r\n var requireRegEx = requireRegExs[requireAlias] || (requireRegExs[requireAlias] = new RegExp(cjsRequirePre + requireAlias + cjsRequirePost, 'g'));\r\n\r\n requireRegEx.lastIndex = 0;\r\n\r\n var deps = [];\r\n\r\n var match;\r\n while (match = requireRegEx.exec(source))\r\n deps.push(match[2] || match[3]);\r\n\r\n return deps;\r\n}\r\n\r\nfunction wrapEsModuleExecute (execute) {\r\n return function (require, exports, module) {\r\n execute(require, exports, module);\r\n exports = module.exports;\r\n if ((typeof exports === 'object' || typeof exports === 'function') && !('__esModule' in exports))\r\n Object.defineProperty(module.exports, '__esModule', {\r\n value: true\r\n });\r\n };\r\n}\r\n\r\n// generate anonymous define from singular named define\r\nvar multipleNamedDefines = false;\r\nvar lastNamedDefine;\r\nvar curMetaDeps;\r\nvar curEsModule = false;\r\nexport function clearLastDefine (metaDeps, esModule) {\r\n curMetaDeps = metaDeps;\r\n curEsModule = esModule;\r\n lastNamedDefine = undefined;\r\n multipleNamedDefines = false;\r\n}\r\nexport function registerLastDefine (loader) {\r\n if (lastNamedDefine)\r\n loader.registerDynamic(curMetaDeps ? lastNamedDefine[0].concat(curMetaDeps) : lastNamedDefine[0],\r\n false, curEsModule ? wrapEsModuleExecute(lastNamedDefine[1]) : lastNamedDefine[1]);\r\n\r\n // bundles are an empty module\r\n else if (multipleNamedDefines)\r\n loader.registerDynamic([], false, noop);\r\n}\r\n","import { scriptLoad, isBrowser, isWorker, global, cjsRequireRegEx, addToError, loadNodeModule,\r\n warn, CONFIG, METADATA, emptyModule, protectedCreateNamespace, resolvedPromise, preloadScript, checkInstantiateWasm } from './common.js';\r\nimport { evaluate } from './evaluate.js';\r\nimport fetch from './fetch.js';\r\nimport { getGlobalValue, getCJSDeps, requireResolve, getPathVars, prepareGlobal, clearLastDefine, registerLastDefine } from './format-helpers.js';\r\n\r\nvar supportsScriptLoad = (isBrowser || isWorker) && typeof navigator !== 'undefined' && navigator.userAgent && !navigator.userAgent.match(/MSIE (9|10).0/);\r\n\r\n// include the node require since we're overriding it\r\nexport var nodeRequire;\r\nif (typeof require !== 'undefined' && typeof process !== 'undefined' && !process.browser)\r\n nodeRequire = require;\r\n\r\nfunction setMetaEsModule (metadata, moduleValue) {\r\n if (metadata.load.esModule && (typeof moduleValue === 'object' || typeof moduleValue === 'function') &&\r\n !('__esModule' in moduleValue))\r\n Object.defineProperty(moduleValue, '__esModule', {\r\n value: true\r\n });\r\n}\r\n\r\nexport function instantiate (key, processAnonRegister) {\r\n var loader = this;\r\n var config = this[CONFIG];\r\n // first do bundles and depCache\r\n return (loadBundlesAndDepCache(config, this, key) || resolvedPromise)\r\n .then(function () {\r\n if (processAnonRegister())\r\n return;\r\n\r\n var metadata = loader[METADATA][key];\r\n\r\n // node module loading\r\n if (key.substr(0, 6) === '@node/') {\r\n if (!loader._nodeRequire)\r\n throw new TypeError('Error loading ' + key + '. Can only load node core modules in Node.');\r\n loader.registerDynamic([], false, function () {\r\n return loadNodeModule.call(loader, key.substr(6), loader.baseURL);\r\n });\r\n processAnonRegister();\r\n return;\r\n }\r\n\r\n if (metadata.load.scriptLoad ) {\r\n if (metadata.load.pluginKey || !supportsScriptLoad) {\r\n metadata.load.scriptLoad = false;\r\n warn.call(config, 'scriptLoad not supported for \"' + key + '\"');\r\n }\r\n }\r\n else if (metadata.load.scriptLoad !== false && !metadata.load.pluginKey && supportsScriptLoad) {\r\n // auto script load AMD, global without deps\r\n if (!metadata.load.deps && !metadata.load.globals &&\r\n (metadata.load.format === 'system' || metadata.load.format === 'register' || metadata.load.format === 'global' && metadata.load.exports))\r\n metadata.load.scriptLoad = true;\r\n }\r\n\r\n // fetch / translate / instantiate pipeline\r\n if (!metadata.load.scriptLoad)\r\n return initializePlugin(loader, key, metadata)\r\n .then(function () {\r\n return runFetchPipeline(loader, key, metadata, processAnonRegister, config.wasm);\r\n })\r\n\r\n // just script loading\r\n return new Promise(function (resolve, reject) {\r\n if (metadata.load.format === 'amd' && global.define !== loader.amdDefine)\r\n throw new Error('Loading AMD with scriptLoad requires setting the global `' + globalName + '.define = SystemJS.amdDefine`');\r\n\r\n scriptLoad(key, metadata.load.crossOrigin, metadata.load.integrity, function () {\r\n if (!processAnonRegister()) {\r\n metadata.load.format = 'global';\r\n var globalValue = metadata.load.exports && getGlobalValue(metadata.load.exports);\r\n loader.registerDynamic([], false, function () {\r\n setMetaEsModule(metadata, globalValue);\r\n return globalValue;\r\n });\r\n processAnonRegister();\r\n }\r\n\r\n resolve();\r\n }, reject);\r\n });\r\n })\r\n .then(function (instantiated) {\r\n delete loader[METADATA][key];\r\n return instantiated;\r\n });\r\n};\r\n\r\nfunction initializePlugin (loader, key, metadata) {\r\n if (!metadata.pluginKey)\r\n return resolvedPromise;\r\n\r\n return loader.import(metadata.pluginKey).then(function (plugin) {\r\n metadata.pluginModule = plugin;\r\n metadata.pluginLoad = {\r\n name: key,\r\n address: metadata.pluginArgument,\r\n source: undefined,\r\n metadata: metadata.load\r\n };\r\n metadata.load.deps = metadata.load.deps || [];\r\n });\r\n}\r\n\r\nfunction loadBundlesAndDepCache (config, loader, key) {\r\n // load direct deps, in turn will pick up their trace trees\r\n var deps;\r\n if (isBrowser && (deps = config.depCache[key])) {\r\n for (var i = 0; i < deps.length; i++)\r\n loader.normalize(deps[i], key).then(preloadScript);\r\n }\r\n else {\r\n var matched = false;\r\n for (var b in config.bundles) {\r\n for (var i = 0; i < config.bundles[b].length; i++) {\r\n var curModule = config.bundles[b][i];\r\n\r\n if (curModule === key) {\r\n matched = true;\r\n break;\r\n }\r\n\r\n // wildcard in bundles includes / boundaries\r\n if (curModule.indexOf('*') !== -1) {\r\n var parts = curModule.split('*');\r\n if (parts.length !== 2) {\r\n config.bundles[b].splice(i--, 1);\r\n continue;\r\n }\r\n\r\n if (key.substr(0, parts[0].length) === parts[0] &&\r\n key.substr(key.length - parts[1].length, parts[1].length) === parts[1]) {\r\n matched = true;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (matched)\r\n return loader.import(b);\r\n }\r\n }\r\n}\r\n\r\nfunction runFetchPipeline (loader, key, metadata, processAnonRegister, wasm) {\r\n if (metadata.load.exports && !metadata.load.format)\r\n metadata.load.format = 'global';\r\n\r\n return resolvedPromise\r\n\r\n // locate\r\n .then(function () {\r\n if (!metadata.pluginModule || !metadata.pluginModule.locate)\r\n return;\r\n\r\n return Promise.resolve(metadata.pluginModule.locate.call(loader, metadata.pluginLoad))\r\n .then(function (address) {\r\n if (address)\r\n metadata.pluginLoad.address = address;\r\n });\r\n })\r\n\r\n // fetch\r\n .then(function () {\r\n if (!metadata.pluginModule)\r\n return fetch(key, metadata.load.authorization, metadata.load.integrity, wasm);\r\n\r\n wasm = false;\r\n\r\n if (!metadata.pluginModule.fetch)\r\n return fetch(metadata.pluginLoad.address, metadata.load.authorization, metadata.load.integrity, false);\r\n\r\n return metadata.pluginModule.fetch.call(loader, metadata.pluginLoad, function (load) {\r\n return fetch(load.address, metadata.load.authorization, metadata.load.integrity, false);\r\n });\r\n })\r\n\r\n .then(function (fetched) {\r\n // fetch is already a utf-8 string if not doing wasm detection\r\n if (!wasm || typeof fetched === 'string')\r\n return translateAndInstantiate(loader, key, fetched, metadata, processAnonRegister);\r\n\r\n return checkInstantiateWasm(loader, fetched, processAnonRegister)\r\n .then(function (wasmInstantiated) {\r\n if (wasmInstantiated)\r\n return;\r\n\r\n // not wasm -> convert buffer into utf-8 string to execute as a module\r\n // TextDecoder compatibility matches WASM currently. Need to keep checking this.\r\n // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder\r\n var stringSource = isBrowser ? new TextDecoder('utf-8').decode(new Uint8Array(fetched)) : fetched.toString();\r\n return translateAndInstantiate(loader, key, stringSource, metadata, processAnonRegister);\r\n });\r\n });\r\n}\r\n\r\nfunction translateAndInstantiate (loader, key, source, metadata, processAnonRegister) {\r\n return Promise.resolve(source)\r\n // translate\r\n .then(function (source) {\r\n if (metadata.load.format === 'detect')\r\n metadata.load.format = undefined;\r\n\r\n readMetaSyntax(source, metadata);\r\n\r\n if (!metadata.pluginModule)\r\n return source;\r\n\r\n metadata.pluginLoad.source = source;\r\n\r\n if (!metadata.pluginModule.translate)\r\n return source;\r\n\r\n return Promise.resolve(metadata.pluginModule.translate.call(loader, metadata.pluginLoad, metadata.traceOpts))\r\n .then(function (translated) {\r\n if (metadata.load.sourceMap) {\r\n if (typeof metadata.load.sourceMap !== 'object')\r\n throw new Error('metadata.load.sourceMap must be set to an object.');\r\n sanitizeSourceMap(metadata.pluginLoad.address, metadata.load.sourceMap);\r\n }\r\n\r\n if (typeof translated === 'string')\r\n return translated;\r\n else\r\n return metadata.pluginLoad.source;\r\n });\r\n })\r\n .then(function (source) {\r\n if (!metadata.load.format && source.substring(0, 8) === '\"bundle\"') {\r\n metadata.load.format = 'system';\r\n return source;\r\n }\r\n\r\n if (metadata.load.format === 'register' || !metadata.load.format && detectRegisterFormat(source)) {\r\n metadata.load.format = 'register';\r\n return source;\r\n }\r\n\r\n if (metadata.load.format !== 'esm' && (metadata.load.format || !source.match(esmRegEx))) {\r\n return source;\r\n }\r\n\r\n metadata.load.format = 'esm';\r\n return transpile(loader, source, key, metadata, processAnonRegister);\r\n })\r\n\r\n // instantiate\r\n .then(function (translated) {\r\n if (typeof translated !== 'string' || !metadata.pluginModule || !metadata.pluginModule.instantiate)\r\n return translated;\r\n\r\n var calledInstantiate = false;\r\n metadata.pluginLoad.source = translated;\r\n return Promise.resolve(metadata.pluginModule.instantiate.call(loader, metadata.pluginLoad, function (load) {\r\n translated = load.source;\r\n metadata.load = load.metadata;\r\n if (calledInstantiate)\r\n throw new Error('Instantiate must only be called once.');\r\n calledInstantiate = true;\r\n }))\r\n .then(function (result) {\r\n if (calledInstantiate)\r\n return translated;\r\n return protectedCreateNamespace(result);\r\n });\r\n })\r\n .then(function (source) {\r\n // plugin instantiate result case\r\n if (typeof source !== 'string')\r\n return source;\r\n\r\n if (!metadata.load.format)\r\n metadata.load.format = detectLegacyFormat(source);\r\n\r\n var registered = false;\r\n\r\n switch (metadata.load.format) {\r\n case 'esm':\r\n case 'register':\r\n case 'system':\r\n var err = evaluate(loader, source, metadata.load.sourceMap, key, metadata.load.integrity, metadata.load.nonce, false);\r\n if (err)\r\n throw err;\r\n if (!processAnonRegister())\r\n return emptyModule;\r\n return;\r\n break;\r\n\r\n case 'json':\r\n // warn.call(config, '\"json\" module format is deprecated.');\r\n var parsed = JSON.parse(source);\r\n return loader.newModule({ default: parsed, __useDefault: parsed });\r\n\r\n case 'amd':\r\n var curDefine = global.define;\r\n global.define = loader.amdDefine;\r\n\r\n clearLastDefine(metadata.load.deps, metadata.load.esModule);\r\n\r\n var err = evaluate(loader, source, metadata.load.sourceMap, key, metadata.load.integrity, metadata.load.nonce, false);\r\n\r\n // if didn't register anonymously, use the last named define if only one\r\n registered = processAnonRegister();\r\n if (!registered) {\r\n registerLastDefine(loader);\r\n registered = processAnonRegister();\r\n }\r\n\r\n global.define = curDefine;\r\n\r\n if (err)\r\n throw err;\r\n break;\r\n\r\n case 'cjs':\r\n var metaDeps = metadata.load.deps;\r\n var deps = (metadata.load.deps || []).concat(metadata.load.cjsRequireDetection ? getCJSDeps(source) : []);\r\n\r\n for (var g in metadata.load.globals)\r\n if (metadata.load.globals[g])\r\n deps.push(metadata.load.globals[g]);\r\n\r\n loader.registerDynamic(deps, true, function (require, exports, module) {\r\n require.resolve = function (key) {\r\n return requireResolve.call(loader, key, module.id);\r\n };\r\n // support module.paths ish\r\n module.paths = [];\r\n module.require = require;\r\n\r\n // ensure meta deps execute first\r\n if (!metadata.load.cjsDeferDepsExecute && metaDeps)\r\n for (var i = 0; i < metaDeps.length; i++)\r\n require(metaDeps[i]);\r\n\r\n var pathVars = getPathVars(module.id);\r\n var __cjsWrapper = {\r\n exports: exports,\r\n args: [require, exports, module, pathVars.filename, pathVars.dirname, global, global]\r\n };\r\n\r\n var cjsWrapper = \"(function (require, exports, module, __filename, __dirname, global, GLOBAL\";\r\n\r\n // add metadata.globals to the wrapper arguments\r\n if (metadata.load.globals)\r\n for (var g in metadata.load.globals) {\r\n __cjsWrapper.args.push(require(metadata.load.globals[g]));\r\n cjsWrapper += \", \" + g;\r\n }\r\n\r\n // disable AMD detection\r\n var define = global.define;\r\n global.define = undefined;\r\n global.__cjsWrapper = __cjsWrapper;\r\n\r\n source = cjsWrapper + \") {\" + source.replace(hashBangRegEx, '') + \"\\n}).apply(__cjsWrapper.exports, __cjsWrapper.args);\";\r\n\r\n var err = evaluate(loader, source, metadata.load.sourceMap, key, metadata.load.integrity, metadata.load.nonce, false);\r\n if (err)\r\n throw err;\r\n\r\n setMetaEsModule(metadata, exports);\r\n\r\n global.__cjsWrapper = undefined;\r\n global.define = define;\r\n });\r\n registered = processAnonRegister();\r\n break;\r\n\r\n case 'global':\r\n var deps = metadata.load.deps || [];\r\n for (var g in metadata.load.globals) {\r\n var gl = metadata.load.globals[g];\r\n if (gl)\r\n deps.push(gl);\r\n }\r\n\r\n loader.registerDynamic(deps, false, function (require, exports, module) {\r\n var globals;\r\n if (metadata.load.globals) {\r\n globals = {};\r\n for (var g in metadata.load.globals)\r\n if (metadata.load.globals[g])\r\n globals[g] = require(metadata.load.globals[g]);\r\n }\r\n\r\n var exportName = metadata.load.exports;\r\n\r\n if (exportName)\r\n source += '\\n' + globalName + '[\"' + exportName + '\"] = ' + exportName + ';';\r\n\r\n var retrieveGlobal = prepareGlobal(module.id, exportName, globals, metadata.load.encapsulateGlobal);\r\n var err = evaluate(loader, source, metadata.load.sourceMap, key, metadata.load.integrity, metadata.load.nonce, true);\r\n\r\n if (err)\r\n throw err;\r\n\r\n var output = retrieveGlobal();\r\n setMetaEsModule(metadata, output);\r\n return output;\r\n });\r\n registered = processAnonRegister();\r\n break;\r\n\r\n default:\r\n throw new TypeError('Unknown module format \"' + metadata.load.format + '\" for \"' + key + '\".' + (metadata.load.format === 'es6' ? ' Use \"esm\" instead here.' : ''));\r\n }\r\n\r\n if (!registered)\r\n throw new Error('Module ' + key + ' detected as ' + metadata.load.format + ' but didn\\'t execute correctly.');\r\n });\r\n}\r\n\r\nvar globalName = typeof self != 'undefined' ? 'self' : 'global';\r\n\r\n// good enough ES6 module detection regex - format detections not designed to be accurate, but to handle the 99% use case\r\nexport var esmRegEx = /(^\\s*|[}\\);\\n]\\s*)(import\\s*(['\"]|(\\*\\s+as\\s+)?(?!type)([^\"'\\(\\)\\n; ]+)\\s*from\\s*['\"]|\\{)|export\\s+\\*\\s+from\\s+[\"']|export\\s*(\\{|default|function|class|var|const|let|async\\s+function))/;\r\n\r\nvar leadingCommentAndMetaRegEx = /^(\\s*\\/\\*[^\\*]*(\\*(?!\\/)[^\\*]*)*\\*\\/|\\s*\\/\\/[^\\n]*|\\s*\"[^\"]+\"\\s*;?|\\s*'[^']+'\\s*;?)*\\s*/;\r\nexport function detectRegisterFormat(source) {\r\n var leadingCommentAndMeta = source.match(leadingCommentAndMetaRegEx);\r\n if (!leadingCommentAndMeta)\r\n return false;\r\n var codeStart = leadingCommentAndMeta[0].length;\r\n return source.startsWith('System.register', codeStart) || source.startsWith('SystemJS.register', codeStart);\r\n}\r\n\r\n// AMD Module Format Detection RegEx\r\n// define([.., .., ..], ...)\r\n// define(varName); || define(function(require, exports) {}); || define({})\r\nvar amdRegEx = /(?:^\\uFEFF?|[^$_a-zA-Z\\xA0-\\uFFFF.])define\\s*\\(\\s*(\"[^\"]+\"\\s*,\\s*|'[^']+'\\s*,\\s*)?\\s*(\\[(\\s*((\"[^\"]+\"|'[^']+')\\s*,|\\/\\/.*\\r?\\n|\\/\\*(.|\\s)*?\\*\\/))*(\\s*(\"[^\"]+\"|'[^']+')\\s*,?)?(\\s*(\\/\\/.*\\r?\\n|\\/\\*(.|\\s)*?\\*\\/))*\\s*\\]|function\\s*|{|[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*\\))/;\r\n\r\n/// require('...') || exports[''] = ... || exports.asd = ... || module.exports = ...\r\nvar cjsExportsRegEx = /(?:^\\uFEFF?|[^$_a-zA-Z\\xA0-\\uFFFF.])(exports\\s*(\\[['\"]|\\.)|module(\\.exports|\\['exports'\\]|\\[\"exports\"\\])\\s*(\\[['\"]|[=,\\.]))/;\r\nvar commentRegEx = /(^|[^\\\\])(\\/\\*([\\s\\S]*?)\\*\\/|([^:]|^)\\/\\/(.*)$)/mg;\r\n\r\nvar stringRegEx = /(\"[^\"\\\\\\n\\r]*(\\\\.[^\"\\\\\\n\\r]*)*\"|'[^'\\\\\\n\\r]*(\\\\.[^'\\\\\\n\\r]*)*')/g;\r\n\r\n// used to support leading #!/usr/bin/env in scripts as supported in Node\r\nvar hashBangRegEx = /^\\#\\!.*/;\r\n\r\nexport function detectLegacyFormat (source) {\r\n if (source.match(amdRegEx))\r\n return 'amd';\r\n\r\n cjsExportsRegEx.lastIndex = 0;\r\n cjsRequireRegEx.lastIndex = 0;\r\n if (cjsRequireRegEx.exec(source) || cjsExportsRegEx.exec(source))\r\n return 'cjs';\r\n\r\n // global is the fallback format\r\n return 'global';\r\n}\r\n\r\nfunction sanitizeSourceMap (address, sourceMap) {\r\n var originalName = address.split('!')[0];\r\n\r\n // force set the filename of the original file\r\n if (!sourceMap.file || sourceMap.file == address)\r\n sourceMap.file = originalName + '!transpiled';\r\n\r\n // force set the sources list if only one source\r\n if (!sourceMap.sources || sourceMap.sources.length <= 1 && (!sourceMap.sources[0] || sourceMap.sources[0] === address))\r\n sourceMap.sources = [originalName];\r\n}\r\n\r\nfunction transpile (loader, source, key, metadata, processAnonRegister) {\r\n if (!loader.transpiler)\r\n throw new TypeError('Unable to dynamically transpile ES module\\n A loader plugin needs to be configured via `SystemJS.config({ transpiler: \\'transpiler-module\\' })`.');\r\n\r\n // deps support for es transpile\r\n if (metadata.load.deps) {\r\n var depsPrefix = '';\r\n for (var i = 0; i < metadata.load.deps.length; i++)\r\n depsPrefix += 'import \"' + metadata.load.deps[i] + '\"; ';\r\n source = depsPrefix + source;\r\n }\r\n\r\n // do transpilation\r\n return loader.import.call(loader, loader.transpiler)\r\n .then(function (transpiler) {\r\n transpiler = transpiler.__useDefault || transpiler;\r\n\r\n // translate hooks means this is a transpiler plugin instead of a raw implementation\r\n if (!transpiler.translate)\r\n throw new Error(loader.transpiler + ' is not a valid transpiler plugin.');\r\n\r\n // if transpiler is the same as the plugin loader, then don't run twice\r\n if (transpiler === metadata.pluginModule)\r\n return source;\r\n\r\n // convert the source map into an object for transpilation chaining\r\n if (typeof metadata.load.sourceMap === 'string')\r\n metadata.load.sourceMap = JSON.parse(metadata.load.sourceMap);\r\n\r\n metadata.pluginLoad = metadata.pluginLoad || {\r\n name: key,\r\n address: key,\r\n source: source,\r\n metadata: metadata.load\r\n };\r\n metadata.load.deps = metadata.load.deps || [];\r\n\r\n return Promise.resolve(transpiler.translate.call(loader, metadata.pluginLoad, metadata.traceOpts))\r\n .then(function (source) {\r\n // sanitize sourceMap if an object not a JSON string\r\n var sourceMap = metadata.load.sourceMap;\r\n if (sourceMap && typeof sourceMap === 'object')\r\n sanitizeSourceMap(key, sourceMap);\r\n\r\n if (metadata.load.format === 'esm' && detectRegisterFormat(source))\r\n metadata.load.format = 'register';\r\n\r\n return source;\r\n });\r\n }, function (err) {\r\n throw addToError(err, 'Unable to load transpiler to transpile ' + key);\r\n });\r\n}\r\n\r\n// detect any meta header syntax\r\n// only set if not already set\r\nvar metaRegEx = /^(\\s*\\/\\*[^\\*]*(\\*(?!\\/)[^\\*]*)*\\*\\/|\\s*\\/\\/[^\\n]*|\\s*\"[^\"]+\"\\s*;?|\\s*'[^']+'\\s*;?)+/;\r\nvar metaPartRegEx = /\\/\\*[^\\*]*(\\*(?!\\/)[^\\*]*)*\\*\\/|\\/\\/[^\\n]*|\"[^\"]+\"\\s*;?|'[^']+'\\s*;?/g;\r\n\r\nfunction setMetaProperty(target, p, value) {\r\n var pParts = p.split('.');\r\n var curPart;\r\n while (pParts.length > 1) {\r\n curPart = pParts.shift();\r\n target = target[curPart] = target[curPart] || {};\r\n }\r\n curPart = pParts.shift();\r\n if (target[curPart] === undefined)\r\n target[curPart] = value;\r\n}\r\n\r\nfunction readMetaSyntax (source, metadata) {\r\n var meta = source.match(metaRegEx);\r\n if (!meta)\r\n return;\r\n\r\n var metaParts = meta[0].match(metaPartRegEx);\r\n\r\n for (var i = 0; i < metaParts.length; i++) {\r\n var curPart = metaParts[i];\r\n var len = curPart.length;\r\n\r\n var firstChar = curPart.substr(0, 1);\r\n if (curPart.substr(len - 1, 1) == ';')\r\n len--;\r\n\r\n if (firstChar != '\"' && firstChar != \"'\")\r\n continue;\r\n\r\n var metaString = curPart.substr(1, curPart.length - 3);\r\n var metaName = metaString.substr(0, metaString.indexOf(' '));\r\n\r\n if (metaName) {\r\n var metaValue = metaString.substr(metaName.length + 1, metaString.length - metaName.length - 1);\r\n\r\n if (metaName === 'deps')\r\n metaName = 'deps[]';\r\n\r\n if (metaName.substr(metaName.length - 2, 2) === '[]') {\r\n metaName = metaName.substr(0, metaName.length - 2);\r\n metadata.load[metaName] = metadata.load[metaName] || [];\r\n metadata.load[metaName].push(metaValue);\r\n }\r\n // \"use strict\" is not meta\r\n else if (metaName !== 'use') {\r\n setMetaProperty(metadata.load, metaName, metaValue);\r\n }\r\n }\r\n else {\r\n metadata.load[metaString] = true;\r\n }\r\n }\r\n}\r\n","import RegisterLoader from 'es-module-loader/core/register-loader.js';\r\nimport { warn, isBrowser, global, baseURI, CONFIG, METADATA, ModuleNamespace, emptyModule, isModule } from './common.js';\r\n\r\nimport { getConfig, getConfigItem, setConfig } from './config.js';\r\nimport { decanonicalize, normalize, normalizeSync } from './resolve.js';\r\nimport { instantiate, nodeRequire } from './instantiate.js';\r\nimport { setHelpers, setAmdHelper } from './format-helpers.js';\r\n\r\nexport default SystemJSLoader;\r\n\r\nvar scriptSrc;\r\n\r\n// Promise detection and error message\r\nif (typeof Promise === 'undefined')\r\n throw new Error('SystemJS needs a Promise polyfill.');\r\n\r\nif (typeof document !== 'undefined') {\r\n var scripts = document.getElementsByTagName('script');\r\n var curScript = scripts[scripts.length - 1];\r\n if (document.currentScript && (curScript.defer || curScript.async))\r\n curScript = document.currentScript;\r\n\r\n scriptSrc = curScript && curScript.src;\r\n}\r\n// worker\r\nelse if (typeof importScripts !== 'undefined') {\r\n try {\r\n throw new Error('_');\r\n }\r\n catch (e) {\r\n e.stack.replace(/(?:at|@).*(http.+):[\\d]+:[\\d]+/, function(m, url) {\r\n scriptSrc = url;\r\n });\r\n }\r\n}\r\n// node\r\nelse if (typeof __filename !== 'undefined') {\r\n scriptSrc = __filename;\r\n}\r\n\r\nfunction SystemJSLoader () {\r\n RegisterLoader.call(this);\r\n\r\n // NB deprecate\r\n this._loader = {};\r\n\r\n // internal metadata store\r\n this[METADATA] = {};\r\n\r\n // internal configuration\r\n this[CONFIG] = {\r\n baseURL: baseURI,\r\n paths: {},\r\n\r\n packageConfigPaths: [],\r\n packageConfigKeys: [],\r\n map: {},\r\n packages: {},\r\n depCache: {},\r\n meta: {},\r\n bundles: {},\r\n\r\n production: false,\r\n\r\n transpiler: undefined,\r\n loadedBundles: {},\r\n\r\n // global behaviour flags\r\n warnings: false,\r\n pluginFirst: false,\r\n\r\n // enable wasm loading and detection when supported\r\n wasm: false\r\n };\r\n\r\n // make the location of the system.js script accessible (if any)\r\n this.scriptSrc = scriptSrc;\r\n\r\n this._nodeRequire = nodeRequire;\r\n\r\n // support the empty module, as a concept\r\n this.registry.set('@empty', emptyModule);\r\n\r\n setProduction.call(this, false, false);\r\n\r\n // add module format helpers\r\n setHelpers(this);\r\n setAmdHelper(this);\r\n}\r\n\r\nexport var envModule;\r\nexport function setProduction (isProduction, isBuilder) {\r\n this[CONFIG].production = isProduction;\r\n this.registry.set('@system-env', envModule = this.newModule({\r\n browser: isBrowser,\r\n node: !!this._nodeRequire,\r\n production: !isBuilder && isProduction,\r\n dev: isBuilder || !isProduction,\r\n build: isBuilder,\r\n 'default': true\r\n }));\r\n}\r\n\r\nSystemJSLoader.prototype = Object.create(RegisterLoader.prototype);\r\n\r\nSystemJSLoader.prototype.constructor = SystemJSLoader;\r\n\r\n// NB deprecate normalize\r\nSystemJSLoader.prototype[SystemJSLoader.resolve = RegisterLoader.resolve] = SystemJSLoader.prototype.normalize = normalize;\r\n\r\nSystemJSLoader.prototype.load = function (key, parentKey) {\r\n warn.call(this[CONFIG], 'System.load is deprecated.');\r\n return this.import(key, parentKey);\r\n};\r\n\r\n// NB deprecate decanonicalize, normalizeSync\r\nSystemJSLoader.prototype.decanonicalize = SystemJSLoader.prototype.normalizeSync = SystemJSLoader.prototype.resolveSync = normalizeSync;\r\n\r\nSystemJSLoader.prototype[SystemJSLoader.instantiate = RegisterLoader.instantiate] = instantiate;\r\n\r\nSystemJSLoader.prototype.config = setConfig;\r\nSystemJSLoader.prototype.getConfig = getConfig;\r\n\r\nSystemJSLoader.prototype.global = global;\r\n\r\nSystemJSLoader.prototype.import = function () {\r\n return RegisterLoader.prototype.import.apply(this, arguments)\r\n .then(function (m) {\r\n return '__useDefault' in m ? m.__useDefault : m;\r\n });\r\n};\r\n\r\nexport var configNames = ['baseURL', 'map', 'paths', 'packages', 'packageConfigPaths', 'depCache', 'meta', 'bundles', 'transpiler', 'warnings', 'pluginFirst', 'production', 'wasm'];\r\n\r\nvar hasProxy = typeof Proxy !== 'undefined';\r\nfor (var i = 0; i < configNames.length; i++) (function (configName) {\r\n Object.defineProperty(SystemJSLoader.prototype, configName, {\r\n get: function () {\r\n var cfg = getConfigItem(this[CONFIG], configName);\r\n\r\n if (hasProxy && typeof cfg === 'object')\r\n cfg = new Proxy(cfg, {\r\n set: function (target, option) {\r\n throw new Error('Cannot set SystemJS.' + configName + '[\"' + option + '\"] directly. Use SystemJS.config({ ' + configName + ': { \"' + option + '\": ... } }) rather.');\r\n }\r\n });\r\n\r\n //if (typeof cfg === 'object')\r\n // warn.call(this[CONFIG], 'Referencing `SystemJS.' + configName + '` is deprecated. Use the config getter `SystemJS.getConfig(\\'' + configName + '\\')`');\r\n return cfg;\r\n },\r\n set: function (name) {\r\n throw new Error('Setting `SystemJS.' + configName + '` directly is no longer supported. Use `SystemJS.config({ ' + configName + ': ... })`.');\r\n }\r\n });\r\n})(configNames[i]);\r\n\r\n/*\r\n * Backwards-compatible registry API, to be deprecated\r\n */\r\nfunction registryWarn(loader, method) {\r\n warn.call(loader[CONFIG], 'SystemJS.' + method + ' is deprecated for SystemJS.registry.' + method);\r\n}\r\nSystemJSLoader.prototype.delete = function (key) {\r\n registryWarn(this, 'delete');\r\n return this.registry.delete(key);\r\n};\r\nSystemJSLoader.prototype.get = function (key) {\r\n registryWarn(this, 'get');\r\n return this.registry.get(key);\r\n};\r\nSystemJSLoader.prototype.has = function (key) {\r\n registryWarn(this, 'has');\r\n return this.registry.has(key);\r\n};\r\nSystemJSLoader.prototype.set = function (key, module) {\r\n registryWarn(this, 'set');\r\n return this.registry.set(key, module);\r\n};\r\nSystemJSLoader.prototype.newModule = function (bindings) {\r\n return new ModuleNamespace(bindings);\r\n};\r\nSystemJSLoader.prototype.isModule = isModule;\r\n\r\n// ensure System.register and System.registerDynamic decanonicalize\r\nSystemJSLoader.prototype.register = function (key, deps, declare) {\r\n if (typeof key === 'string')\r\n key = decanonicalize.call(this, this[CONFIG], key);\r\n return RegisterLoader.prototype.register.call(this, key, deps, declare);\r\n};\r\n\r\nSystemJSLoader.prototype.registerDynamic = function (key, deps, executingRequire, execute) {\r\n if (typeof key === 'string')\r\n key = decanonicalize.call(this, this[CONFIG], key);\r\n return RegisterLoader.prototype.registerDynamic.call(this, key, deps, executingRequire, execute);\r\n};\r\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nconst operators_1 = require(\"rxjs/operators\");\nconst request_1 = require(\"../request\");\nconst file_1 = require(\"../file\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger/bootstrap-logger\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst compression_service_1 = require(\"../compression/compression.service\");\nconst npm_service_1 = require(\"../npm-service/npm.service\");\nconst providers_1 = require(\"./providers\");\nconst SystemJS = require(\"systemjs\");\nlet ExternalImporter = class ExternalImporter {\n constructor() {\n this.defaultJsonFolder = `${process.cwd()}/package.json`;\n this.defaultTypescriptConfigJsonFolder = `${process.cwd()}/tsconfig.json`;\n this.providers = new rxjs_1.BehaviorSubject(providers_1.IPFS_PROVIDERS);\n this.defaultProvider = this.getProvider('main-ipfs-node');\n this.defaultNamespaceFolder = '@types';\n this.defaultOutputFolder = 'node_modules';\n }\n setDefaultProvider(provider) {\n this.defaultProvider = this.getProvider(provider);\n }\n getProvider(name) {\n return this.providers.getValue().filter(p => p.name === name)[0].link;\n }\n setProviders(...args) {\n this.providers.next([...this.providers.getValue(), ...args]);\n }\n importExternalModule(module) {\n return rxjs_1.from(SystemJS.import(module));\n }\n validateConfig(config) {\n if (!config) {\n throw new Error('Bootstrap: missing config');\n }\n }\n // encryptFile(fileFullPath: string) {\n // if (this.configService.config.experimental.crypto) {\n // return this.compressionService.readGzipFile(fileFullPath, 'dada');\n // } else {\n // return of(null);\n // }\n // }\n // decryptFile(fileFullPath: string) {\n // if (this.configService.config.experimental.crypto) {\n // return this.compressionService.gZipFile(fileFullPath, 'dada');\n // } else {\n // return of(null);\n // }\n // }\n isWeb() {\n let value = false;\n try {\n if (window) {\n value = true;\n }\n }\n catch (e) { }\n return value;\n }\n loadTypescriptConfigJson() {\n let tsConfig = {};\n try {\n tsConfig = this.fileService.readFile(this.defaultTypescriptConfigJsonFolder);\n }\n catch (e) {\n console.error(`\n Error in loading tsconfig.json in ${this.defaultTypescriptConfigJsonFolder}\n Error: ${e}\n Fallback to creating tsconfig.json\n `);\n }\n tsConfig.compilerOptions = tsConfig.compilerOptions || {};\n tsConfig.compilerOptions.typeRoots =\n tsConfig.compilerOptions.typeRoots || [];\n return tsConfig;\n }\n addNamespaceToTypeRoots(namespace) {\n const defaultNamespace = `./${this.defaultOutputFolder}/@types/${namespace}`;\n const tsConfig = this.loadTypescriptConfigJson();\n const foundNamespace = tsConfig.compilerOptions.typeRoots.filter(t => t === defaultNamespace).length;\n if (!foundNamespace) {\n tsConfig.compilerOptions.typeRoots.push(defaultNamespace);\n this.writeTypescriptConfigFile(tsConfig);\n }\n return rxjs_1.of(true);\n }\n writeTypescriptConfigFile(file) {\n this.fileService.writeFileSync(process.cwd() + '/tsconfig.json', file);\n }\n loadPackageJson() {\n let packageJson;\n try {\n packageJson = this.fileService.readFile(this.defaultJsonFolder);\n }\n catch (e) {\n packageJson = {};\n }\n return packageJson;\n }\n loadNpmPackageJson() {\n let packageJson;\n try {\n packageJson = this.fileService.readFile(`${process.cwd()}/package.json`);\n }\n catch (e) {\n packageJson = {};\n }\n return packageJson;\n }\n prepareDependencies() {\n const file = this.loadNpmPackageJson();\n if (file.dependencies) {\n return Object.keys(file.dependencies).map(name => ({\n name,\n version: file.dependencies[name]\n }));\n }\n return [];\n }\n isModulePresent(hash) {\n const file = this.loadPackageJson();\n let ipfsConfig = file.ipfs;\n const found = [];\n if (!ipfsConfig) {\n ipfsConfig = this.defaultIpfsConfig();\n }\n ipfsConfig.forEach(c => {\n const present = c.dependencies.filter(dep => dep === hash);\n if (present.length) {\n found.push(present[0]);\n }\n });\n return found.length;\n }\n filterUniquePackages() {\n const file = this.loadPackageJson();\n let ipfsConfig = file.ipfs;\n let dups = [];\n if (!ipfsConfig) {\n ipfsConfig = this.defaultIpfsConfig();\n }\n ipfsConfig.forEach(c => {\n const uniq = c.dependencies\n .map(name => {\n return { count: 1, name: name };\n })\n .reduce((a, b) => {\n a[b.name] = (a[b.name] || 0) + b.count;\n return a;\n }, {});\n const duplicates = Object.keys(uniq).filter(a => uniq[a] > 1);\n dups = [...dups, ...duplicates];\n });\n if (dups.length) {\n throw new Error(`There are packages which are with the same hash ${JSON.stringify(dups)}`);\n }\n return dups.length;\n }\n defaultIpfsConfig() {\n return [{ provider: this.defaultProvider, dependencies: [] }];\n }\n addPackageToJson(hash) {\n const file = this.loadPackageJson();\n let ipfsConfig = file.ipfs;\n if (!ipfsConfig) {\n ipfsConfig = this.defaultIpfsConfig();\n }\n const packages = this.prepareDependencies();\n if (packages.length) {\n file.packages = packages;\n }\n if (this.isModulePresent(hash)) {\n this.logger.log(`Package with hash: ${hash} present and will not be downloaded!`);\n }\n else {\n ipfsConfig[0].dependencies.push(hash);\n file.ipfs = ipfsConfig;\n }\n this.fileService.writeFileSync(this.defaultJsonFolder, file);\n }\n downloadIpfsModules(modules) {\n const latest = modules.map(m => this.downloadIpfsModule(m));\n return rxjs_1.combineLatest(latest.length ? latest : rxjs_1.of());\n }\n downloadIpfsModuleConfig(config) {\n return this.requestService\n .get(config.provider + config.hash, config.hash)\n .pipe(operators_1.map(r => {\n if (!r) {\n throw new Error('Recieved undefined from provided address' +\n config.provider +\n config.hash);\n }\n let res = r;\n const metaString = '';\n if (res.includes(metaString)) {\n try {\n res = r.split(metaString)[1];\n }\n catch (e) { }\n }\n return res;\n }), operators_1.map(r => {\n let res = r;\n try {\n res = JSON.parse(r);\n }\n catch (e) { }\n return res;\n }));\n }\n combineDependencies(dependencies, config) {\n return rxjs_1.combineLatest(dependencies.length\n ? dependencies.map(h => this.downloadIpfsModule({ provider: config.provider, hash: h }))\n : rxjs_1.of(''));\n }\n writeFakeIndexIfMultiModule(folder, nameSpaceFakeIndex) {\n if (nameSpaceFakeIndex.length === 2) {\n return this.fileService.writeFileAsyncP(`${folder}${this.defaultNamespaceFolder}/${nameSpaceFakeIndex[0]}`, 'index.d.ts', '');\n }\n else {\n return rxjs_1.of(true);\n }\n }\n downloadIpfsModule(config) {\n if (!config.provider) {\n throw new Error(`Missing configuration inside ${config.hash}`);\n }\n if (!config.hash) {\n throw new Error(`Missing configuration inside ${config.provider}`);\n }\n let folder;\n let moduleLink;\n const configLink = config.provider + config.hash;\n let moduleTypings;\n let moduleName;\n let nameSpaceFakeIndex;\n let originalModuleConfig;\n let isNamespace;\n let isRegular;\n return this.downloadIpfsModuleConfig(config).pipe(operators_1.tap(res => {\n if (!res['module']) {\n console.log('Todo: create logic to load module which is not from rxdi infrastructure for now can be used useDynamic which will do the same job!');\n }\n }), operators_1.filter((res) => !!res.module), operators_1.map((externalModule) => {\n moduleName = externalModule.name;\n nameSpaceFakeIndex = moduleName.split('/');\n folder = `${process.cwd()}/${this.defaultOutputFolder}/`;\n moduleLink = `${config.provider}${externalModule.module}`;\n moduleTypings = `${config.provider}${externalModule.typings}`;\n externalModule.dependencies = externalModule.dependencies || [];\n externalModule.packages = externalModule.packages || [];\n originalModuleConfig = externalModule;\n this.npmService.setPackages(externalModule.packages);\n isNamespace = moduleName.split('/').length === 2;\n isRegular = isNamespace ? moduleName : moduleName.split('/')[0];\n this.logger.logFileService(`Package config for module ${moduleName} downloaded! ${JSON.stringify(externalModule)}`);\n return externalModule;\n }), operators_1.switchMap(externalModule => this.combineDependencies(externalModule.dependencies, config)), operators_1.switchMap(() => {\n this.logger.logFileService(`--------------------${moduleName}--------------------`);\n this.logger.logFileService(`\\nDownloading... ${configLink} `);\n this.logger.logFileService(`Config: ${JSON.stringify(originalModuleConfig, null, 2)} \\n`);\n return this.requestService.get(moduleLink, config.hash);\n }), operators_1.switchMap(file => this.fileService.writeFile(folder + moduleName, 'index.js', moduleName, file)), operators_1.switchMap(() => this.requestService.get(moduleTypings, config.hash)), operators_1.switchMap(file => this.fileService.writeFile(folder + `${this.defaultNamespaceFolder}/${isRegular}`, 'index.d.ts', moduleName, file)), operators_1.tap(() => {\n if (process.env.WRITE_FAKE_INDEX) {\n this.writeFakeIndexIfMultiModule(folder, nameSpaceFakeIndex);\n }\n }), operators_1.switchMap(() => this.addNamespaceToTypeRoots(moduleName.split('/')[0])), operators_1.map(() => ({\n provider: config.provider,\n hash: config.hash,\n version: originalModuleConfig.version,\n name: originalModuleConfig.name,\n dependencies: originalModuleConfig.dependencies,\n packages: originalModuleConfig.packages\n })), operators_1.tap(() => {\n if (originalModuleConfig.packages.length) {\n this.npmService.installPackages();\n }\n }));\n }\n downloadTypings(moduleLink, folder, fileName, config) {\n if (!moduleLink) {\n return rxjs_1.of(true);\n }\n return this.requestService.get(moduleLink).pipe(operators_1.take(1), operators_1.map(res => {\n this.logger.logFileService(`Done!`);\n return res;\n }), operators_1.switchMap(res => this.fileService.writeFile(folder, fileName, config.typingsFileName, res)));\n }\n importModule(config, token, { folderOverride, waitUntil } = {}) {\n const timer$ = rxjs_1.timer(waitUntil || 20 * 1000);\n this.validateConfig(config);\n if (this.isWeb()) {\n SystemJS.config(Object.assign({\n map: {\n [token]: config.link\n }\n }, config.SystemJsConfig));\n return SystemJS.import(config.link);\n }\n return new rxjs_1.Observable(observer => {\n const moduleName = config.fileName;\n const moduleNamespace = config.namespace;\n const moduleLink = config.link;\n const moduleExtension = config.extension;\n const moduleSystemJsConfig = config.SystemJsConfig || {};\n const modulesFolder = config.outputFolder || `/${this.defaultOutputFolder}/`;\n const fileFullPath = `${folderOverride ||\n process.cwd()}${modulesFolder}/${moduleNamespace}/${moduleName}.${moduleExtension}`;\n const folder = `${folderOverride ||\n process.cwd()}${modulesFolder}${moduleNamespace}`;\n const fileName = `${moduleName}.${moduleExtension}`;\n Object.assign(moduleSystemJsConfig, {\n paths: Object.assign({ [moduleName]: fileFullPath }, moduleSystemJsConfig.paths)\n });\n SystemJS.config(moduleSystemJsConfig);\n if (this.fileService.isPresent(fileFullPath)) {\n this.logger.logImporter(`Bootstrap -> @Service('${moduleName}'): present inside .${modulesFolder}${moduleNamespace}/${moduleName}.${moduleExtension} folder and loaded from there`);\n this.importExternalModule(moduleName)\n .pipe(operators_1.take(1))\n .subscribe(m => {\n observer.next(m);\n observer.complete();\n }, err => {\n observer.error(err);\n observer.complete();\n });\n }\n else {\n this.logger.logImporter(`Bootstrap -> @Service('${moduleName}'): will be downloaded inside .${modulesFolder}${moduleNamespace}/${moduleName}.${moduleExtension} folder and loaded from there`);\n this.logger.logImporter(`Bootstrap -> @Service('${moduleName}'): ${moduleLink} downloading...`);\n this.requestService\n .get(moduleLink)\n .pipe(operators_1.take(1), operators_1.tap(() => this.logger.logImporter(`Done!`)), operators_1.switchMap(res => this.fileService.writeFile(folder, fileName, config.fileName, res)), operators_1.switchMap(() => this.downloadTypings(config.typings, folder, fileName, config)), operators_1.switchMap(() => this.importExternalModule(moduleName)))\n .subscribe(m => {\n observer.next(m);\n observer.complete();\n }, err => {\n observer.error(err);\n observer.complete();\n });\n }\n })\n .pipe(operators_1.takeUntil(timer$))\n .toPromise();\n }\n};\n__decorate([\n injector_decorator_1.Injector(request_1.RequestService),\n __metadata(\"design:type\", request_1.RequestService)\n], ExternalImporter.prototype, \"requestService\", void 0);\n__decorate([\n injector_decorator_1.Injector(file_1.FileService),\n __metadata(\"design:type\", file_1.FileService)\n], ExternalImporter.prototype, \"fileService\", void 0);\n__decorate([\n injector_decorator_1.Injector(bootstrap_logger_1.BootstrapLogger),\n __metadata(\"design:type\", bootstrap_logger_1.BootstrapLogger)\n], ExternalImporter.prototype, \"logger\", void 0);\n__decorate([\n injector_decorator_1.Injector(compression_service_1.CompressionService),\n __metadata(\"design:type\", compression_service_1.CompressionService)\n], ExternalImporter.prototype, \"compressionService\", void 0);\n__decorate([\n injector_decorator_1.Injector(npm_service_1.NpmService),\n __metadata(\"design:type\", npm_service_1.NpmService)\n], ExternalImporter.prototype, \"npmService\", void 0);\nExternalImporter = __decorate([\n Service_1.Service()\n], ExternalImporter);\nexports.ExternalImporter = ExternalImporter;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass ExternalImporterConfig {\n}\nexports.ExternalImporterConfig = ExternalImporterConfig;\nclass ExternalImporterIpfsConfig {\n}\nexports.ExternalImporterIpfsConfig = ExternalImporterIpfsConfig;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./external-importer\"));\n__export(require(\"./external-importer-config\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet LazyFactory = class LazyFactory {\n constructor() {\n this.lazyFactories = new Map();\n }\n setLazyFactory(provide, factory) {\n this.lazyFactories.set(provide, factory);\n return this.getLazyFactory(provide);\n }\n getLazyFactory(provide) {\n return this.lazyFactories.get(provide);\n }\n};\nLazyFactory = __decorate([\n Service_1.Service()\n], LazyFactory);\nexports.LazyFactory = LazyFactory;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../../decorators/service/Service\");\nlet ModuleValidators = class ModuleValidators {\n validateEmpty(m, original, type) {\n if (!m) {\n const requiredType = type.charAt(0).toUpperCase() + type.slice(1);\n throw new Error(`\n ${original.metadata.raw}\n -> @Module: ${original.metadata.moduleName}\n -> @Module hash: ${original.metadata.moduleHash}\n --> Maybe you forgot to import some ${requiredType} inside ${original.metadata.moduleName} ?\n\n Hint: run ts-lint again, looks like imported ${requiredType} is undefined or null inside ${original.metadata.moduleName}\n `);\n }\n }\n genericWrongPluggableError(m, original, type) {\n if (m.metadata.type !== type) {\n const moduleType = m.metadata.type.charAt(0).toUpperCase() + m.metadata.type.slice(1);\n const requiredType = type.charAt(0).toUpperCase() + type.slice(1);\n throw new Error(`\n ${original.metadata.raw}\n -> @Module: '${original.metadata.moduleName}'\n -> @Module hash: '${original.metadata.moduleHash}'\n --> @${moduleType} '${m.metadata.moduleName}' provided, where expected class decorated with '@${requiredType}' instead,\n -> @Hint: please provide class with @Service decorator or remove ${m.metadata.moduleName} class\n `);\n }\n }\n validateImports(m, original) {\n if (m.metadata.type !== 'module') {\n throw new Error(`\n ${original.metadata.raw}\n -> @Module: '${original.metadata.moduleName}'\n -> @Module hash: '${original.metadata.moduleHash}'\n --> @${m.metadata.type.charAt(0).toUpperCase() +\n m.metadata.type.slice(1)} '${m.originalName}' provided, where expected class decorated with '@Module' instead,\n -> @Hint: please provide class with @Module decorator or remove ${m.originalName} from imports\n `);\n }\n }\n validateServices(m, original) {\n this.validateEmpty(m, original, 'service');\n if (m.provide) {\n return;\n }\n this.genericWrongPluggableError(m, original, 'service');\n }\n validatePlugin(m, original) {\n this.validateEmpty(m, original, 'plugin');\n if (m.provide) {\n return;\n }\n this.genericWrongPluggableError(m, original, 'plugin');\n }\n validateController(m, original) {\n this.validateEmpty(m, original, 'controller');\n if (m.provide) {\n return;\n }\n this.genericWrongPluggableError(m, original, 'controller');\n }\n validateEffect(m, original) {\n this.validateEmpty(m, original, 'effect');\n if (m.provide) {\n return;\n }\n this.genericWrongPluggableError(m, original, 'effect');\n }\n validateComponent(m, original) {\n this.validateEmpty(m, original, 'component');\n if (m.provide) {\n return;\n }\n this.genericWrongPluggableError(m, original, 'component');\n }\n};\nModuleValidators = __decorate([\n Service_1.Service()\n], ModuleValidators);\nexports.ModuleValidators = ModuleValidators;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet ControllersService = class ControllersService {\n constructor() {\n this.controllers = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.controllers.next([...this.controllers.getValue(), plugin]);\n }\n getControllers() {\n return this.controllers.getValue();\n }\n};\nControllersService = __decorate([\n Service_1.Service()\n], ControllersService);\nexports.ControllersService = ControllersService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet EffectsService = class EffectsService {\n constructor() {\n this.effects = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.effects.next([...this.effects.getValue(), plugin]);\n }\n getEffects() {\n return this.effects.getValue();\n }\n};\nEffectsService = __decorate([\n Service_1.Service()\n], EffectsService);\nexports.EffectsService = EffectsService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet ComponentsService = class ComponentsService {\n constructor() {\n this.components = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.components.next([...this.components.getValue(), plugin]);\n }\n getComponents() {\n return this.components.getValue();\n }\n};\nComponentsService = __decorate([\n Service_1.Service()\n], ComponentsService);\nexports.ComponentsService = ComponentsService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet BootstrapsServices = class BootstrapsServices {\n constructor() {\n this.bootstraps = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.bootstraps.next([...this.bootstraps.getValue(), plugin]);\n }\n getBootstraps() {\n return this.bootstraps.getValue();\n }\n};\nBootstrapsServices = __decorate([\n Service_1.Service()\n], BootstrapsServices);\nexports.BootstrapsServices = BootstrapsServices;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet ServicesService = class ServicesService {\n constructor() {\n this.services = new rxjs_1.BehaviorSubject([]);\n }\n register(plugin) {\n this.services.next([...this.services.getValue(), plugin]);\n }\n getServices() {\n return this.services.getValue();\n }\n};\nServicesService = __decorate([\n Service_1.Service()\n], ServicesService);\nexports.ServicesService = ServicesService;\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rxjs_1 = require(\"rxjs\");\nconst container_1 = require(\"../../container\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst lazy_factory_service_1 = require(\"../lazy-factory/lazy-factory.service\");\nconst plugin_service_1 = require(\"../plugin/plugin.service\");\nconst external_importer_1 = require(\"../external-importer\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst validators_1 = require(\"./helpers/validators\");\nconst constructor_watcher_1 = require(\"../constructor-watcher/constructor-watcher\");\nconst controllers_service_1 = require(\"../controllers/controllers.service\");\nconst effect_service_1 = require(\"../effect/effect.service\");\nconst components_service_1 = require(\"../components/components.service\");\nconst bootstraps_service_1 = require(\"../bootstraps/bootstraps.service\");\nconst services_service_1 = require(\"../services/services.service\");\nlet ModuleService = class ModuleService {\n constructor() {\n this.watcherService = constructor_watcher_1.constructorWatcherService;\n }\n setServices(services, original, currentModule) {\n services.forEach(service => {\n this.validators.validateServices(service, original);\n this.setInjectedDependencies(service);\n if (service.provide && service.provide.constructor === Function) {\n service.provide = service.provide['name'];\n }\n if (service.provide && service.useFactory) {\n this.setUseFactory(service);\n }\n else if (service.provide && service.useDynamic) {\n this.setUseDynamic(service);\n }\n else if (service.provide &&\n service.useClass &&\n service.useClass.constructor === Function) {\n this.setUseClass(service);\n }\n else if (service.provide && service.useValue) {\n this.setUseValue(service);\n }\n else {\n currentModule.putItem({ data: service, key: service.name });\n this.servicesService.register(service);\n }\n });\n }\n setInjectedDependencies(service) {\n service.deps = service.deps || [];\n if (service.deps.length) {\n service.deps = service.deps.map(dep => container_1.Container.get(dep));\n }\n }\n setUseValue(service) {\n container_1.Container.set(service.provide, service.useValue);\n if (service.lazy) {\n this.lazyFactoryService.setLazyFactory(service.provide, rxjs_1.of(container_1.Container.get(service.provide)));\n }\n }\n setUseClass(service) {\n if (service.lazy) {\n this.lazyFactoryService.setLazyFactory(service.provide, rxjs_1.of(container_1.Container.get(service.useClass)));\n }\n else {\n container_1.Container.set(service.provide, container_1.Container.get(service.useClass));\n }\n }\n setUseDynamic(service) {\n const factory = this.externalImporter.importModule(service.useDynamic, service.provide);\n this.lazyFactoryService.setLazyFactory(service.provide, factory);\n }\n setUseFactory(service) {\n const factory = service.useFactory;\n service.useFactory = () => factory(...service.deps);\n if (service.lazy) {\n this.lazyFactoryService.setLazyFactory(service.provide, service.useFactory());\n }\n else {\n container_1.Container.set(service.provide, service.useFactory());\n }\n }\n setControllers(controllers, original, currentModule) {\n controllers.forEach(controller => {\n this.validators.validateController(controller, original);\n currentModule.putItem({\n data: controller,\n key: controller.name\n });\n this.controllersService.register(controller);\n });\n }\n setEffects(effects, original, currentModule) {\n effects.forEach(effect => {\n this.validators.validateEffect(effect, original);\n currentModule.putItem({\n data: effect,\n key: effect.name\n });\n this.effectsService.register(effect);\n });\n }\n setComponents(components, original, currentModule) {\n components.forEach(component => {\n this.validators.validateComponent(component, original);\n currentModule.putItem({\n data: component,\n key: component.name\n });\n this.componentsService.register(component);\n });\n }\n setPlugins(plugins, original, currentModule) {\n plugins.forEach(plugin => {\n this.validators.validatePlugin(plugin, original);\n currentModule.putItem({\n data: plugin,\n key: plugin.name\n });\n this.pluginService.register(plugin);\n });\n }\n setBootstraps(bootstraps, original, currentModule) {\n bootstraps.forEach(bootstrap => {\n this.validators.validateEmpty(bootstrap, original, bootstrap['metadata']['type']);\n currentModule.putItem({\n data: bootstrap,\n key: bootstrap.name\n });\n this.bootstraps.register(bootstrap);\n });\n }\n setAfterPlugins(plugins, original, currentModule) {\n plugins.forEach(plugin => {\n this.validators.validatePlugin(plugin, original);\n currentModule.putItem({\n data: plugin,\n key: plugin.name\n });\n this.pluginService.registerAfter(plugin);\n });\n }\n setBeforePlugins(plugins, original, currentModule) {\n plugins.forEach(plugin => {\n this.validators.validatePlugin(plugin, original);\n currentModule.putItem({\n data: plugin,\n key: plugin.name\n });\n this.pluginService.registerBefore(plugin);\n });\n }\n setImports(imports, original) {\n imports.forEach((m) => {\n this.validators.validateImports(m, original);\n if (!m) {\n throw new Error('Missing import module');\n }\n else {\n container_1.Container.get(m);\n }\n });\n }\n};\n__decorate([\n injector_decorator_1.Injector(lazy_factory_service_1.LazyFactory),\n __metadata(\"design:type\", lazy_factory_service_1.LazyFactory)\n], ModuleService.prototype, \"lazyFactoryService\", void 0);\n__decorate([\n injector_decorator_1.Injector(plugin_service_1.PluginService),\n __metadata(\"design:type\", plugin_service_1.PluginService)\n], ModuleService.prototype, \"pluginService\", void 0);\n__decorate([\n injector_decorator_1.Injector(components_service_1.ComponentsService),\n __metadata(\"design:type\", components_service_1.ComponentsService)\n], ModuleService.prototype, \"componentsService\", void 0);\n__decorate([\n injector_decorator_1.Injector(controllers_service_1.ControllersService),\n __metadata(\"design:type\", controllers_service_1.ControllersService)\n], ModuleService.prototype, \"controllersService\", void 0);\n__decorate([\n injector_decorator_1.Injector(effect_service_1.EffectsService),\n __metadata(\"design:type\", effect_service_1.EffectsService)\n], ModuleService.prototype, \"effectsService\", void 0);\n__decorate([\n injector_decorator_1.Injector(bootstraps_service_1.BootstrapsServices),\n __metadata(\"design:type\", bootstraps_service_1.BootstrapsServices)\n], ModuleService.prototype, \"bootstraps\", void 0);\n__decorate([\n injector_decorator_1.Injector(external_importer_1.ExternalImporter),\n __metadata(\"design:type\", external_importer_1.ExternalImporter)\n], ModuleService.prototype, \"externalImporter\", void 0);\n__decorate([\n injector_decorator_1.Injector(validators_1.ModuleValidators),\n __metadata(\"design:type\", validators_1.ModuleValidators)\n], ModuleService.prototype, \"validators\", void 0);\n__decorate([\n injector_decorator_1.Injector(services_service_1.ServicesService),\n __metadata(\"design:type\", services_service_1.ServicesService)\n], ModuleService.prototype, \"servicesService\", void 0);\nModuleService = __decorate([\n Service_1.Service()\n], ModuleService);\nexports.ModuleService = ModuleService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./module.service\"));\n__export(require(\"./helpers/validators\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst container_1 = require(\"../../container\");\nconst cache_layer_service_1 = require(\"../cache/cache-layer.service\");\nconst events_1 = require(\"../../helpers/events\");\nconst operators_1 = require(\"rxjs/operators\");\nconst rxjs_1 = require(\"rxjs\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger/bootstrap-logger\");\nconst injector_decorator_1 = require(\"../../decorators/injector/injector.decorator\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet ResolverService = class ResolverService {\n resolveDependencies(hash, target, moduleName) {\n this.cacheService\n .getLayer(events_1.InternalLayers.modules)\n .putItem({ key: hash, data: target });\n const currentModule = this.cacheService.getLayer(hash);\n currentModule.putItem({\n key: events_1.InternalEvents.config,\n data: { moduleName, moduleHash: hash }\n });\n return currentModule.getItemObservable(events_1.InternalEvents.load).pipe(operators_1.switchMap(config => {\n if (!config.data) {\n return rxjs_1.of(null);\n }\n return currentModule.items.asObservable();\n }), operators_1.filter(res => res && res.length), operators_1.map(this.resolveContainerDependencies(target, moduleName)));\n }\n resolveContainerDependencies(target, moduleName) {\n return res => {\n res.forEach(i => {\n if (i.key === events_1.InternalEvents.load || i.key === events_1.InternalEvents.config) {\n return;\n }\n const found = this.cacheService.searchForItem(i.data);\n if (found) {\n if (found.provide) {\n return found;\n }\n const moduleType = found.metadata.type.charAt(0).toUpperCase() +\n found.metadata.type.slice(1);\n this.bootstrapLogger.log(`Start -> @Module('${moduleName}')${this.bootstrapLogger.logHashes(`(${target.name})`)}: @${moduleType}('${found.originalName}')${this.bootstrapLogger.logHashes(`(${found.name})`)}` +\n ' initialized!');\n return container_1.Container.get(found);\n }\n else {\n throw new Error('not found');\n }\n });\n return res;\n };\n }\n};\n__decorate([\n injector_decorator_1.Injector(bootstrap_logger_1.BootstrapLogger),\n __metadata(\"design:type\", bootstrap_logger_1.BootstrapLogger)\n], ResolverService.prototype, \"bootstrapLogger\", void 0);\n__decorate([\n injector_decorator_1.Injector(cache_layer_service_1.CacheService),\n __metadata(\"design:type\", cache_layer_service_1.CacheService)\n], ResolverService.prototype, \"cacheService\", void 0);\nResolverService = __decorate([\n Service_1.Service()\n], ResolverService);\nexports.ResolverService = ResolverService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./resolver.service\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst rxjs_1 = require(\"rxjs\");\nlet AfterStarterService = class AfterStarterService {\n constructor() {\n this.appStarted = new rxjs_1.Subject();\n }\n};\nAfterStarterService = __decorate([\n Service_1.Service()\n], AfterStarterService);\nexports.AfterStarterService = AfterStarterService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Container_1 = require(\"../container/Container\");\nexports.logExtendedInjectables = (name, logExtendedInjectables) => {\n if (Container_1.Container.has(name) && logExtendedInjectables) {\n console.log(`Warn: Injection Token '${name.name ||\n name}' is extended after it has being declared! ${JSON.stringify(Container_1.Container.get(name))}`);\n }\n};\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst rxjs_1 = require(\"rxjs\");\nconst container_1 = require(\"../../container\");\nconst bootstrap_logger_1 = require(\"../bootstrap-logger/bootstrap-logger\");\nconst cache_layer_service_1 = require(\"../cache/cache-layer.service\");\nconst events_1 = require(\"../../helpers/events\");\nconst lazy_factory_service_1 = require(\"../lazy-factory/lazy-factory.service\");\nconst config_service_1 = require(\"../config/config.service\");\nconst plugin_service_1 = require(\"../plugin/plugin.service\");\nconst operators_1 = require(\"rxjs/operators\");\nconst effect_service_1 = require(\"../effect/effect.service\");\nconst controllers_service_1 = require(\"../controllers/controllers.service\");\nconst components_service_1 = require(\"../components/components.service\");\nconst bootstraps_service_1 = require(\"../bootstraps/bootstraps.service\");\nconst services_service_1 = require(\"../services/services.service\");\nconst after_starter_service_1 = require(\"../after-starter/after-starter.service\");\nconst log_1 = require(\"../../helpers/log\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet BootstrapService = class BootstrapService {\n constructor(logger, cacheService, lazyFactoriesService, configService, controllersService, effectsService, pluginService, componentsService, bootstrapsService, servicesService, afterStarterService) {\n this.logger = logger;\n this.cacheService = cacheService;\n this.lazyFactoriesService = lazyFactoriesService;\n this.configService = configService;\n this.controllersService = controllersService;\n this.effectsService = effectsService;\n this.pluginService = pluginService;\n this.componentsService = componentsService;\n this.bootstrapsService = bootstrapsService;\n this.servicesService = servicesService;\n this.afterStarterService = afterStarterService;\n this.globalConfig = this.cacheService.createLayer({\n name: events_1.InternalLayers.globalConfig\n });\n }\n start(app, config) {\n this.configService.setConfig(config);\n this.globalConfig.putItem({ key: events_1.InternalEvents.config, data: config });\n container_1.Container.get(app);\n const lazyFactoryKeys = Array.from(this.lazyFactoriesService.lazyFactories.keys());\n return rxjs_1.of(lazyFactoryKeys).pipe(operators_1.map(factories => this.prepareAsyncChainables(factories)), operators_1.switchMap(res => rxjs_1.combineLatest(res).pipe(operators_1.take(1), operators_1.map(c => this.attachLazyLoadedChainables(lazyFactoryKeys, c)), operators_1.map(() => this.validateSystem()), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainableControllers())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainablePluginsBeforeRegister())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainablePluginsRegister())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainablePluginsAfterRegister())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainableServices())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainableEffects())), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainableComponents())), operators_1.map(() => this.loadApplication()), operators_1.switchMap(() => rxjs_1.combineLatest(this.asyncChainableBootstraps())), operators_1.map(() => this.final()))));\n }\n final() {\n this.afterStarterService.appStarted.next(true);\n if (!this.configService.config.init) {\n this.logger.log('Bootstrap -> press start!');\n }\n return container_1.Container;\n }\n asyncChainableComponents() {\n return [\n rxjs_1.of(true),\n ...this.componentsService\n .getComponents()\n .filter(c => this.genericFilter(c, 'components'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield container_1.Container.get(c); }))\n ];\n }\n asyncChainableBootstraps() {\n return [\n rxjs_1.of(true),\n ...this.bootstrapsService\n .getBootstraps()\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield container_1.Container.get(c); }))\n ];\n }\n asyncChainableEffects() {\n return [\n rxjs_1.of(true),\n ...this.effectsService\n .getEffects()\n .filter(c => this.genericFilter(c, 'effects'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield container_1.Container.get(c); }))\n ];\n }\n asyncChainableServices() {\n return [\n rxjs_1.of(true),\n ...this.servicesService\n .getServices()\n .filter(c => this.genericFilter(c, 'services'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield container_1.Container.get(c); }))\n ];\n }\n asyncChainableControllers() {\n return [\n rxjs_1.of(true),\n ...this.controllersService\n .getControllers()\n .filter(c => this.genericFilter(c, 'controllers'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield container_1.Container.get(c); }))\n ];\n }\n asyncChainablePluginsRegister() {\n return [\n rxjs_1.of(true),\n ...this.pluginService\n .getPlugins()\n .filter(c => this.genericFilter(c, 'plugins'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield this.registerPlugin(c); }))\n ];\n }\n asyncChainablePluginsAfterRegister() {\n return [\n rxjs_1.of(true),\n ...this.pluginService\n .getAfterPlugins()\n .filter(c => this.genericFilter(c, 'pluginsAfter'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield this.registerPlugin(c); }))\n ];\n }\n asyncChainablePluginsBeforeRegister() {\n return [\n rxjs_1.of(true),\n ...this.pluginService\n .getBeforePlugins()\n .filter(c => this.genericFilter(c, 'pluginsBefore'))\n .map((c) => __awaiter(this, void 0, void 0, function* () { return yield this.registerPlugin(c); }))\n ];\n }\n genericFilter(c, name) {\n return (this.configService.config.initOptions[name] ||\n (c.metadata.options && c.metadata.options['init']) ||\n this.configService.config.init);\n }\n registerPlugin(pluggable) {\n return __awaiter(this, void 0, void 0, function* () {\n const plugin = container_1.Container.get(pluggable);\n yield plugin.register();\n return plugin;\n });\n }\n prepareAsyncChainables(injectables) {\n const asynChainables = [rxjs_1.of(true)];\n const injectableLog = {};\n const getName = n => n.name || n;\n injectables.map(i => {\n const date = Date.now();\n injectableLog[getName(i)] = {\n started: date,\n end: null\n };\n this.logger.log(`Bootstrap -> @Service('${getName(i)}'): loading...`);\n const somethingAsync = rxjs_1.from((this.lazyFactoriesService.getLazyFactory(i))).pipe(operators_1.shareReplay(1));\n asynChainables.push(somethingAsync);\n somethingAsync.subscribe(() => {\n this.logger.log(`Bootstrap -> @Service('${getName(i)}'): loading finished after ${Date.now() -\n injectableLog[getName(i)].started}ms !`);\n delete injectableLog[getName(i)];\n });\n });\n return asynChainables;\n }\n validateSystem() {\n if (this.configService.config.strict) {\n this.cacheService.searchForDuplicateDependenciesInsideApp();\n }\n }\n attachLazyLoadedChainables(res, chainables) {\n // Remove first chainable unused observable\n chainables.splice(0, 1);\n let count = 0;\n res.map(name => {\n log_1.logExtendedInjectables(name, this.configService.config.experimental.logExtendedInjectables);\n container_1.Container.set(name, chainables[count++]);\n });\n return true;\n }\n loadApplication() {\n Array.from(this.cacheService.getLayer(events_1.InternalLayers.modules).map.keys()).forEach(m => this.cacheService.getLayer(m).putItem({\n key: events_1.InternalEvents.load,\n data: this.configService.config.init\n }));\n return true;\n }\n};\nBootstrapService = __decorate([\n Service_1.Service(),\n __metadata(\"design:paramtypes\", [bootstrap_logger_1.BootstrapLogger,\n cache_layer_service_1.CacheService,\n lazy_factory_service_1.LazyFactory,\n config_service_1.ConfigService,\n controllers_service_1.ControllersService,\n effect_service_1.EffectsService,\n plugin_service_1.PluginService,\n components_service_1.ComponentsService,\n bootstraps_service_1.BootstrapsServices,\n services_service_1.ServicesService,\n after_starter_service_1.AfterStarterService])\n], BootstrapService);\nexports.BootstrapService = BootstrapService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst exit_handler_service_1 = require(\"../services/exit-handler/exit-handler.service\");\nconst container_1 = require(\"../container\");\nexports.exitHandlerInit = () => {\n const handler = container_1.Container.get(exit_handler_service_1.ExitHandlerService);\n handler.init();\n // do something when app is closing\n process.on('exit', handler.exitHandler.bind(handler, { cleanup: true }));\n // catches ctrl+c event\n process.on('SIGINT', handler.exitHandler.bind(handler, { exit: true }));\n // catches 'kill pid' (for example: nodemon restart)\n process.on('SIGUSR1', handler.exitHandler.bind(handler, { exit: true }));\n process.on('SIGUSR2', handler.exitHandler.bind(handler, { exit: true }));\n // catches uncaught exceptions\n process.on('uncaughtException', handler.exitHandler.bind(handler, { exit: true }));\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nrequire(\"reflect-metadata\");\nconst container_1 = require(\"../container\");\nconst bootstrap_service_1 = require(\"../services/bootstrap/bootstrap.service\");\nconst exit_handler_1 = require(\"./exit-handler\");\nexit_handler_1.exitHandlerInit();\nconst bootstrapService = container_1.Container.get(bootstrap_service_1.BootstrapService);\nexports.Bootstrap = (app, config) => bootstrapService.start(app, config);\nexports.BootstrapPromisify = (app, config) => bootstrapService.start(app, config).toPromise();\nexports.BootstrapFramework = (app, modules, config) => {\n bootstrapService.configService.setConfig(config);\n modules.map(m => container_1.Container.get(m));\n return bootstrapService.start(app, config);\n};\nexports.setup = (options, frameworks = [], bootstrapOptions) => {\n const Module = require('../decorators/module/module.decorator').Module;\n return exports.BootstrapFramework(Module({\n imports: options.imports || [],\n providers: options.providers || [],\n services: options.services || [],\n bootstrap: options.bootstrap || [],\n components: options.components || [],\n controllers: options.controllers || [],\n effects: options.effects || [],\n plugins: options.plugins || [],\n afterPlugins: options.afterPlugins || [],\n beforePlugins: options.beforePlugins || []\n })(function () { }), frameworks, bootstrapOptions);\n};\nexports.createTestBed = exports.setup;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./bootstrap\"));\n__export(require(\"./create-unique-hash\"));\n__export(require(\"./generic-constructor\"));\n__export(require(\"./sha256\"));\n// export * from './testing';\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Service_1 = require(\"../../decorators/service/Service\");\nconst helpers_1 = require(\"../../helpers\");\nlet MetadataService = class MetadataService {\n generateHashData(module, original) {\n const services = module.services || [];\n const imports = module.imports || [];\n const fillMetadata = injectable => {\n if (injectable && injectable['provide']) {\n return injectable['provide'];\n }\n else if (injectable) {\n this.validateCustomInjectable(injectable, module, original);\n return {\n moduleName: injectable['metadata']['moduleName'],\n hash: injectable['metadata']['moduleHash']\n };\n }\n };\n return [\n [...services.map(i => fillMetadata(i))],\n [...imports.map(i => fillMetadata(i))]\n ];\n }\n validateCustomInjectableKeys(keys) {\n // keys.forEach(key => {\n // console.log('TOVA NE E SHEGA', key);\n // });\n }\n validateCustomInjectable(injectable, module, original) {\n if (!injectable['metadata'] && !injectable['provide']) {\n throw new Error(`\n ---- Wrong service ${JSON.stringify(injectable)} provided inside '${original.name}' ----\n @Module({\n services: ${JSON.stringify([\n ...module.services.filter(i => !i['metadata']),\n ...module.services\n .filter(i => i && i['metadata'] && i['metadata']['moduleName'])\n .map(i => i['metadata']['moduleName'])\n ])}\n })\n ${JSON.stringify(`${original}`, null, 2)}\n\n Hint: System recieved Object but it is not with appropriate format you must provide object with following parameters:\n\n YourObject: ${JSON.stringify(injectable)}\n\n Option 1. [YourClass]\n\n Option 2. [{provide: 'your-value', useClass: YourClass}]\n\n Option 3. [{provide: 'your-value', deps: [YourClass], useFactory: (test: YourClass) => {}}]\n\n Option 4. [{provide: 'your-value', useDynamic: {}}]\n\n Option 5. [{provide: 'your-value', useValue: 'your-value'}]\n `);\n }\n }\n parseModuleTemplate(moduleName, generatedHashData, targetCurrentSymbol) {\n return `\n ---- @gapi module '${moduleName}' metadata----\n @Module({\n imports: ${JSON.stringify(generatedHashData[1], null, '\\t')},\n services: ${JSON.stringify(generatedHashData[0], null, '\\t')}\n })\n ${JSON.stringify(targetCurrentSymbol, null, 2)}\n `;\n }\n createUniqueHash(string) {\n return helpers_1.createUniqueHash(string);\n }\n};\nMetadataService = __decorate([\n Service_1.Service()\n], MetadataService);\nexports.MetadataService = MetadataService;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./metadata.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./compression.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./effect.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./controllers.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./components.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./bootstraps.service\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./services.service\"));\n","\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst plugin_service_1 = require(\"../plugin/plugin.service\");\nconst Service_1 = require(\"../../decorators/service/Service\");\nlet PluginManager = class PluginManager {\n constructor(pluginService) {\n this.pluginService = pluginService;\n }\n listPlugins() {\n return this.pluginService.getPlugins();\n }\n getPlugin(pluginClass) {\n return this.pluginService\n .getPlugins()\n .filter(p => p.name === pluginClass.name)[0];\n }\n};\nPluginManager = __decorate([\n Service_1.Service(),\n __metadata(\"design:paramtypes\", [plugin_service_1.PluginService])\n], PluginManager);\nexports.PluginManager = PluginManager;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./cache/index\"));\n__export(require(\"./plugin/plugin.service\"));\n__export(require(\"./bootstrap-logger/index\"));\n__export(require(\"./exit-handler/index\"));\n__export(require(\"./external-importer/index\"));\n__export(require(\"./module/index\"));\n__export(require(\"./resolver/index\"));\n__export(require(\"./config/index\"));\n__export(require(\"./metadata/index\"));\n__export(require(\"./compression/index\"));\n__export(require(\"./file/index\"));\n__export(require(\"./constructor-watcher/index\"));\n__export(require(\"./effect/index\"));\n__export(require(\"./controllers/index\"));\n__export(require(\"./components/index\"));\n__export(require(\"./bootstraps/index\"));\n__export(require(\"./services/index\"));\n__export(require(\"./plugin-manager/plugin-manager\"));\n__export(require(\"./after-starter/after-starter.service\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst container_1 = require(\"../container\");\nconst services_1 = require(\"../services\");\nconst moduleService = container_1.Container.get(services_1.ModuleService);\nconst bootstrapLogger = container_1.Container.get(services_1.BootstrapLogger);\nfunction GenericConstruct(module, original, currentModule) {\n return function construct(constructor, args) {\n if (!module) {\n return new constructor();\n }\n if (module.imports) {\n moduleService.setImports(module.imports, original);\n }\n if (module.services) {\n moduleService.setServices(module.services, original, currentModule);\n }\n if (module.providers) {\n moduleService.setServices(module.providers, original, currentModule);\n }\n if (module.controllers) {\n moduleService.setControllers(module.controllers, original, currentModule);\n }\n if (module.effects) {\n moduleService.setEffects(module.effects, original, currentModule);\n }\n if (module.components) {\n moduleService.setComponents(module.components, original, currentModule);\n }\n if (module.beforePlugins) {\n moduleService.setBeforePlugins(module.beforePlugins, original, currentModule);\n }\n if (module.plugins) {\n moduleService.setPlugins(module.plugins, original, currentModule);\n }\n if (module.afterPlugins) {\n moduleService.setAfterPlugins(module.afterPlugins, original, currentModule);\n }\n if (module.bootstrap) {\n moduleService.setBootstraps(module.bootstrap, original, currentModule);\n }\n bootstrapLogger.log(`Bootstrap -> @Module('${constructor.originalName}')${bootstrapLogger.logHashes(`(${constructor.name})`)}: finished!`);\n return container_1.Container.get(constructor);\n };\n}\nexports.GenericConstruct = GenericConstruct;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst container_1 = require(\"../../container\");\nconst cache_layer_service_1 = require(\"../../services/cache/cache-layer.service\");\nconst generic_constructor_1 = require(\"../../helpers/generic-constructor\");\nconst bootstrap_logger_1 = require(\"../../services/bootstrap-logger/bootstrap-logger\");\nconst resolver_service_1 = require(\"../../services/resolver/resolver.service\");\nconst metadata_service_1 = require(\"../../services/metadata/metadata.service\");\nconst module_service_1 = require(\"../../services/module/module.service\");\nconst bootstrapLogger = container_1.Container.get(bootstrap_logger_1.BootstrapLogger);\nconst resolverService = container_1.Container.get(resolver_service_1.ResolverService);\nconst cacheService = container_1.Container.get(cache_layer_service_1.CacheService);\nconst metadataService = container_1.Container.get(metadata_service_1.MetadataService);\nconst moduleService = container_1.Container.get(module_service_1.ModuleService);\nfunction Module(module) {\n return (target) => {\n module = module || {};\n const original = Object.assign(target);\n const moduleName = target.name || target.constructor.name;\n const generatedHashData = metadataService.generateHashData(module, original);\n const uniqueModuleTemplate = metadataService.parseModuleTemplate(moduleName, generatedHashData, `${target}`);\n const uniqueHashForClass = metadataService.createUniqueHash(uniqueModuleTemplate);\n // console.log(`--------- ${moduleName} --------- Hash: ${uniqueHashForClass}---------`);\n // console.log(uniqueModuleTemplate);\n Object.defineProperty(original, 'originalName', { value: original.name || original.constructor.name, writable: false });\n Object.defineProperty(original, 'name', { value: uniqueHashForClass, writable: true });\n const currentModuleLayer = cacheService.createLayer({ name: uniqueHashForClass });\n original.metadata = {\n moduleName: original.originalName,\n moduleHash: uniqueHashForClass,\n options: null,\n type: 'module',\n raw: uniqueModuleTemplate\n };\n const constructorFunction = function (...args) {\n bootstrapLogger.log(`Bootstrap -> @Module('${original.originalName}')${bootstrapLogger.logHashes(`(${original.name})`)}: loading...`);\n return generic_constructor_1.GenericConstruct(module, original, currentModuleLayer)(original, args);\n };\n Object.assign(constructorFunction, original);\n resolverService.resolveDependencies(uniqueHashForClass, original, moduleName)\n .subscribe(() => bootstrapLogger.log(`Start -> @Module('${original.originalName}')${bootstrapLogger.logHashes(`(${original.name})`)}: loaded!`));\n Object.getOwnPropertyNames(original)\n .filter(prop => typeof original[prop] === 'function')\n .map(descriptor => Object.defineProperty(constructorFunction, descriptor, {\n configurable: true,\n writable: true,\n value: original[descriptor]\n }));\n if (original.forRoot) {\n const originalForRoot = constructorFunction.forRoot;\n constructorFunction.forRoot = function (...args) {\n const result = originalForRoot(...args);\n if (!result) {\n throw new Error(`forRoot configuration inside ${constructorFunction.name} is returning undefined or null`);\n }\n if (result.frameworkImports) {\n moduleService.setImports(result.frameworkImports, original);\n }\n if (result.services) {\n moduleService.setServices(result.services, original, currentModuleLayer);\n }\n if (result.providers) {\n moduleService.setServices(result.providers, original, currentModuleLayer);\n }\n if (result.components) {\n moduleService.setComponents(result.components, original, currentModuleLayer);\n }\n if (result.effects) {\n moduleService.setEffects(result.effects, original, currentModuleLayer);\n }\n if (result.controllers) {\n moduleService.setControllers(result.controllers, original, currentModuleLayer);\n }\n if (result.beforePlugins) {\n moduleService.setBeforePlugins(result.beforePlugins, original, currentModuleLayer);\n }\n if (result.plugins) {\n moduleService.setPlugins(result.plugins, original, currentModuleLayer);\n }\n if (result.afterPlugins) {\n moduleService.setAfterPlugins(result.afterPlugins, original, currentModuleLayer);\n }\n /** @angular compatability */\n if (result.ngModule) {\n return result.ngModule;\n }\n return result.module ? result.module : result;\n };\n }\n const service = {\n type: constructorFunction\n };\n container_1.Container.set(service);\n return constructorFunction;\n };\n}\nexports.Module = Module;\n/** @angular module compatability */\nexports.NgModule = Module;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./module.decorator\"));\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./injector.decorator\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst container_1 = require(\"../../container\");\nconst module_service_1 = require(\"../../services/module/module.service\");\nfunction InjectSoft(Service) {\n return container_1.Container.get(module_service_1.ModuleService).watcherService.getByClass(Service);\n}\nexports.InjectSoft = InjectSoft;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./inject-soft.decorator\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Thrown when DI cannot inject value into property decorated by @Inject decorator.\n */\nclass CannotInjectError extends Error {\n constructor(target, propertyName) {\n super(`Cannot inject value into '${target.constructor.name}.${propertyName}'. ` +\n `Please make sure you setup reflect-metadata properly and you don't use interfaces without service tokens as injection value.`);\n this.name = 'ServiceNotFoundError';\n Object.setPrototypeOf(this, CannotInjectError.prototype);\n }\n}\nexports.CannotInjectError = CannotInjectError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Token_1 = require(\"../container/Token\");\nconst CannotInjectError_1 = require(\"../container/error/CannotInjectError\");\nexports.getIdentifier = (typeOrName, target, propertyName) => {\n let identifier;\n if (typeof typeOrName === 'string') {\n identifier = typeOrName;\n }\n else if (typeOrName instanceof Token_1.Token) {\n identifier = typeOrName;\n }\n else {\n identifier = typeOrName();\n }\n if (identifier === Object) {\n throw new CannotInjectError_1.CannotInjectError(target, propertyName);\n }\n return identifier;\n};\nexports.isClient = () => typeof window !== 'undefined' && typeof window.document !== 'undefined';\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Container_1 = require(\"../../container/Container\");\nconst get_identifier_1 = require(\"../../helpers/get-identifier\");\n/**\n * Injects a service into a class property or constructor parameter.\n */\nfunction Inject(typeOrName) {\n return function (target, propertyName, index) {\n if (get_identifier_1.isClient() && typeOrName && typeof typeOrName === 'function') {\n Object.defineProperty(target, propertyName, {\n get: () => Container_1.Container.get(typeOrName)\n });\n return;\n }\n if (!typeOrName)\n typeOrName = () => Reflect.getMetadata('design:type', target, propertyName);\n Container_1.Container.registerHandler({\n object: target,\n propertyName: propertyName,\n index: index,\n value: instance => instance.get(get_identifier_1.getIdentifier(typeOrName, target, propertyName))\n });\n };\n}\nexports.Inject = Inject;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst reflect_decorator_1 = require(\"../../helpers/reflect.decorator\");\nfunction Controller(options) {\n return reflect_decorator_1.ReflectDecorator(options, { type: 'controller' });\n}\nexports.Controller = Controller;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./controller.decorator\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst reflect_decorator_1 = require(\"../../helpers/reflect.decorator\");\nfunction Effect(options) {\n return reflect_decorator_1.ReflectDecorator(options, { type: 'effect' });\n}\nexports.Effect = Effect;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./effect.decorator\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst reflect_decorator_1 = require(\"../../helpers/reflect.decorator\");\nfunction Plugin(options) {\n return reflect_decorator_1.ReflectDecorator(options, { type: 'plugin' });\n}\nexports.Plugin = Plugin;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst reflect_decorator_1 = require(\"../../helpers/reflect.decorator\");\nfunction Component(options) {\n return reflect_decorator_1.ReflectDecorator(options, { type: 'component' });\n}\nexports.Component = Component;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./component.decorator\"));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Container_1 = require(\"../../container/Container\");\nconst Token_1 = require(\"../../container/Token\");\nconst get_identifier_1 = require(\"../../helpers/get-identifier\");\n/**\n * Injects a service into a class property or constructor parameter.\n */\nfunction InjectMany(typeOrName) {\n return function (target, propertyName, index) {\n if (get_identifier_1.isClient() && typeOrName instanceof Token_1.Token) {\n Object.defineProperty(target, propertyName, {\n get: () => Container_1.Container.getMany(get_identifier_1.getIdentifier(typeOrName, target, propertyName))\n });\n return;\n }\n if (!typeOrName) {\n typeOrName = () => Reflect.getMetadata('design:type', target, propertyName);\n }\n Container_1.Container.registerHandler({\n object: target,\n propertyName: propertyName,\n index: index,\n value: instance => instance.getMany(get_identifier_1.getIdentifier(typeOrName, target, propertyName))\n });\n };\n}\nexports.InjectMany = InjectMany;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./module/index\"));\n__export(require(\"./injector/index\"));\n__export(require(\"./inject-soft/index\"));\n__export(require(\"./inject/Inject\"));\n__export(require(\"./controller/index\"));\n__export(require(\"./effect/index\"));\n__export(require(\"./plugin/Plugin\"));\n__export(require(\"./service/Service\"));\n__export(require(\"./component/index\"));\n__export(require(\"./inject-many/InjectMany\"));\nvar Service_1 = require(\"./service/Service\");\nexports.Injectable = Service_1.Service;\n","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\nrequire(\"reflect-metadata\");\n__export(require(\"./container/index\"));\n__export(require(\"./decorators/index\"));\n__export(require(\"./helpers/index\"));\n__export(require(\"./services/index\"));\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst directives = new WeakMap();\n/**\n * Brands a function as a directive factory function so that lit-html will call\n * the function during template rendering, rather than passing as a value.\n *\n * A _directive_ is a function that takes a Part as an argument. It has the\n * signature: `(part: Part) => void`.\n *\n * A directive _factory_ is a function that takes arguments for data and\n * configuration and returns a directive. Users of directive usually refer to\n * the directive factory as the directive. For example, \"The repeat directive\".\n *\n * Usually a template author will invoke a directive factory in their template\n * with relevant arguments, which will then return a directive function.\n *\n * Here's an example of using the `repeat()` directive factory that takes an\n * array and a function to render an item:\n *\n * ```js\n * html`
    <${repeat(items, (item) => html`
  • ${item}
  • `)}
`\n * ```\n *\n * When `repeat` is invoked, it returns a directive function that closes over\n * `items` and the template function. When the outer template is rendered, the\n * return directive function is called with the Part for the expression.\n * `repeat` then performs it's custom logic to render multiple items.\n *\n * @param f The directive factory function. Must be a function that returns a\n * function of the signature `(part: Part) => void`. The returned function will\n * be called with the part object.\n *\n * @example\n *\n * import {directive, html} from 'lit-html';\n *\n * const immutable = directive((v) => (part) => {\n * if (part.value !== v) {\n * part.setValue(v)\n * }\n * });\n */\nexports.directive = (f) => ((...args) => {\n const d = f(...args);\n directives.set(d, true);\n return d;\n});\nexports.isDirective = (o) => {\n return typeof o === 'function' && directives.has(o);\n};\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * True if the custom elements polyfill is in use.\n */\nexports.isCEPolyfill = window.customElements !== undefined &&\n window.customElements.polyfillWrapFlushCallback !==\n undefined;\n/**\n * Reparents nodes, starting from `start` (inclusive) to `end` (exclusive),\n * into another container (could be the same container), before `before`. If\n * `before` is null, it appends the nodes to the container.\n */\nexports.reparentNodes = (container, start, end = null, before = null) => {\n while (start !== end) {\n const n = start.nextSibling;\n container.insertBefore(start, before);\n start = n;\n }\n};\n/**\n * Removes nodes, starting from `start` (inclusive) to `end` (exclusive), from\n * `container`.\n */\nexports.removeNodes = (container, start, end = null) => {\n while (start !== end) {\n const n = start.nextSibling;\n container.removeChild(start);\n start = n;\n }\n};\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2018 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexports.noChange = {};\n/**\n * A sentinel value that signals a NodePart to fully clear its content.\n */\nexports.nothing = {};\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An expression marker with embedded unique key to avoid collision with\n * possible text in templates.\n */\nexports.marker = `{{lit-${String(Math.random()).slice(2)}}}`;\n/**\n * An expression marker used text-positions, multi-binding attributes, and\n * attributes with markup-like text values.\n */\nexports.nodeMarker = ``;\nexports.markerRegex = new RegExp(`${exports.marker}|${exports.nodeMarker}`);\n/**\n * Suffix appended to all bound attribute names.\n */\nexports.boundAttributeSuffix = '$lit$';\n/**\n * An updateable Template that tracks the location of dynamic parts.\n */\nclass Template {\n constructor(result, element) {\n this.parts = [];\n this.element = element;\n const nodesToRemove = [];\n const stack = [];\n // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null\n const walker = document.createTreeWalker(element.content, 133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */, null, false);\n // Keeps track of the last index associated with a part. We try to delete\n // unnecessary nodes, but we never want to associate two different parts\n // to the same index. They must have a constant node between.\n let lastPartIndex = 0;\n let index = -1;\n let partIndex = 0;\n const { strings, values: { length } } = result;\n while (partIndex < length) {\n const node = walker.nextNode();\n if (node === null) {\n // We've exhausted the content inside a nested template element.\n // Because we still have parts (the outer for-loop), we know:\n // - There is a template in the stack\n // - The walker will find a nextNode outside the template\n walker.currentNode = stack.pop();\n continue;\n }\n index++;\n if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {\n if (node.hasAttributes()) {\n const attributes = node.attributes;\n const { length } = attributes;\n // Per\n // https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap,\n // attributes are not guaranteed to be returned in document order.\n // In particular, Edge/IE can return them out of order, so we cannot\n // assume a correspondence between part index and attribute index.\n let count = 0;\n for (let i = 0; i < length; i++) {\n if (endsWith(attributes[i].name, exports.boundAttributeSuffix)) {\n count++;\n }\n }\n while (count-- > 0) {\n // Get the template literal section leading up to the first\n // expression in this attribute\n const stringForPart = strings[partIndex];\n // Find the attribute name\n const name = exports.lastAttributeNameRegex.exec(stringForPart)[2];\n // Find the corresponding attribute\n // All bound attributes have had a suffix added in\n // TemplateResult#getHTML to opt out of special attribute\n // handling. To look up the attribute value we also need to add\n // the suffix.\n const attributeLookupName = name.toLowerCase() + exports.boundAttributeSuffix;\n const attributeValue = node.getAttribute(attributeLookupName);\n node.removeAttribute(attributeLookupName);\n const statics = attributeValue.split(exports.markerRegex);\n this.parts.push({ type: 'attribute', index, name, strings: statics });\n partIndex += statics.length - 1;\n }\n }\n if (node.tagName === 'TEMPLATE') {\n stack.push(node);\n walker.currentNode = node.content;\n }\n }\n else if (node.nodeType === 3 /* Node.TEXT_NODE */) {\n const data = node.data;\n if (data.indexOf(exports.marker) >= 0) {\n const parent = node.parentNode;\n const strings = data.split(exports.markerRegex);\n const lastIndex = strings.length - 1;\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for node parts\n for (let i = 0; i < lastIndex; i++) {\n let insert;\n let s = strings[i];\n if (s === '') {\n insert = exports.createMarker();\n }\n else {\n const match = exports.lastAttributeNameRegex.exec(s);\n if (match !== null && endsWith(match[2], exports.boundAttributeSuffix)) {\n s = s.slice(0, match.index) + match[1] +\n match[2].slice(0, -exports.boundAttributeSuffix.length) + match[3];\n }\n insert = document.createTextNode(s);\n }\n parent.insertBefore(insert, node);\n this.parts.push({ type: 'node', index: ++index });\n }\n // If there's no text, we must insert a comment to mark our place.\n // Else, we can trust it will stick around after cloning.\n if (strings[lastIndex] === '') {\n parent.insertBefore(exports.createMarker(), node);\n nodesToRemove.push(node);\n }\n else {\n node.data = strings[lastIndex];\n }\n // We have a part for each match found\n partIndex += lastIndex;\n }\n }\n else if (node.nodeType === 8 /* Node.COMMENT_NODE */) {\n if (node.data === exports.marker) {\n const parent = node.parentNode;\n // Add a new marker node to be the startNode of the Part if any of\n // the following are true:\n // * We don't have a previousSibling\n // * The previousSibling is already the start of a previous part\n if (node.previousSibling === null || index === lastPartIndex) {\n index++;\n parent.insertBefore(exports.createMarker(), node);\n }\n lastPartIndex = index;\n this.parts.push({ type: 'node', index });\n // If we don't have a nextSibling, keep this node so we have an end.\n // Else, we can remove it to save future costs.\n if (node.nextSibling === null) {\n node.data = '';\n }\n else {\n nodesToRemove.push(node);\n index--;\n }\n partIndex++;\n }\n else {\n let i = -1;\n while ((i = node.data.indexOf(exports.marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n // TODO (justinfagnani): consider whether it's even worth it to\n // make bindings in comments work\n this.parts.push({ type: 'node', index: -1 });\n partIndex++;\n }\n }\n }\n }\n // Remove text binding nodes after the walk to not disturb the TreeWalker\n for (const n of nodesToRemove) {\n n.parentNode.removeChild(n);\n }\n }\n}\nexports.Template = Template;\nconst endsWith = (str, suffix) => {\n const index = str.length - suffix.length;\n return index >= 0 && str.slice(index) === suffix;\n};\nexports.isTemplatePartActive = (part) => part.index !== -1;\n// Allows `document.createComment('')` to be renamed for a\n// small manual size-savings.\nexports.createMarker = () => document.createComment('');\n/**\n * This regex extracts the attribute name preceding an attribute-position\n * expression. It does this by matching the syntax allowed for attributes\n * against the string literal directly preceding the expression, assuming that\n * the expression is in an attribute-value position.\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\x09\\x0a\\x0c\\x0d\" are HTML space characters:\n * https://www.w3.org/TR/html5/infrastructure.html#space-characters\n *\n * \"\\0-\\x1F\\x7F-\\x9F\" are Unicode control characters, which includes every\n * space character except \" \".\n *\n * So an attribute is:\n * * The name: any character except a control character, space character, ('),\n * (\"), \">\", \"=\", or \"/\"\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nexports.lastAttributeNameRegex = /([ \\x09\\x0a\\x0c\\x0d])([^\\0-\\x1F\\x7F-\\x9F \"'>=/]+)([ \\x09\\x0a\\x0c\\x0d]*=[ \\x09\\x0a\\x0c\\x0d]*(?:[^ \\x09\\x0a\\x0c\\x0d\"'`<>=]*|\"[^\"]*|'[^']*))$/;\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @module lit-html\n */\nconst dom_1 = require(\"./dom\");\nconst template_1 = require(\"./template\");\n/**\n * An instance of a `Template` that can be attached to the DOM and updated\n * with new values.\n */\nclass TemplateInstance {\n constructor(template, processor, options) {\n this.__parts = [];\n this.template = template;\n this.processor = processor;\n this.options = options;\n }\n update(values) {\n let i = 0;\n for (const part of this.__parts) {\n if (part !== undefined) {\n part.setValue(values[i]);\n }\n i++;\n }\n for (const part of this.__parts) {\n if (part !== undefined) {\n part.commit();\n }\n }\n }\n _clone() {\n // There are a number of steps in the lifecycle of a template instance's\n // DOM fragment:\n // 1. Clone - create the instance fragment\n // 2. Adopt - adopt into the main document\n // 3. Process - find part markers and create parts\n // 4. Upgrade - upgrade custom elements\n // 5. Update - set node, attribute, property, etc., values\n // 6. Connect - connect to the document. Optional and outside of this\n // method.\n //\n // We have a few constraints on the ordering of these steps:\n // * We need to upgrade before updating, so that property values will pass\n // through any property setters.\n // * We would like to process before upgrading so that we're sure that the\n // cloned fragment is inert and not disturbed by self-modifying DOM.\n // * We want custom elements to upgrade even in disconnected fragments.\n //\n // Given these constraints, with full custom elements support we would\n // prefer the order: Clone, Process, Adopt, Upgrade, Update, Connect\n //\n // But Safari dooes not implement CustomElementRegistry#upgrade, so we\n // can not implement that order and still have upgrade-before-update and\n // upgrade disconnected fragments. So we instead sacrifice the\n // process-before-upgrade constraint, since in Custom Elements v1 elements\n // must not modify their light DOM in the constructor. We still have issues\n // when co-existing with CEv0 elements like Polymer 1, and with polyfills\n // that don't strictly adhere to the no-modification rule because shadow\n // DOM, which may be created in the constructor, is emulated by being placed\n // in the light DOM.\n //\n // The resulting order is on native is: Clone, Adopt, Upgrade, Process,\n // Update, Connect. document.importNode() performs Clone, Adopt, and Upgrade\n // in one step.\n //\n // The Custom Elements v1 polyfill supports upgrade(), so the order when\n // polyfilled is the more ideal: Clone, Process, Adopt, Upgrade, Update,\n // Connect.\n const fragment = dom_1.isCEPolyfill ?\n this.template.element.content.cloneNode(true) :\n document.importNode(this.template.element.content, true);\n const stack = [];\n const parts = this.template.parts;\n // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null\n const walker = document.createTreeWalker(fragment, 133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */, null, false);\n let partIndex = 0;\n let nodeIndex = 0;\n let part;\n let node = walker.nextNode();\n // Loop through all the nodes and parts of a template\n while (partIndex < parts.length) {\n part = parts[partIndex];\n if (!template_1.isTemplatePartActive(part)) {\n this.__parts.push(undefined);\n partIndex++;\n continue;\n }\n // Progress the tree walker until we find our next part's node.\n // Note that multiple parts may share the same node (attribute parts\n // on a single element), so this loop may not run at all.\n while (nodeIndex < part.index) {\n nodeIndex++;\n if (node.nodeName === 'TEMPLATE') {\n stack.push(node);\n walker.currentNode = node.content;\n }\n if ((node = walker.nextNode()) === null) {\n // We've exhausted the content inside a nested template element.\n // Because we still have parts (the outer for-loop), we know:\n // - There is a template in the stack\n // - The walker will find a nextNode outside the template\n walker.currentNode = stack.pop();\n node = walker.nextNode();\n }\n }\n // We've arrived at our part's node.\n if (part.type === 'node') {\n const part = this.processor.handleTextExpression(this.options);\n part.insertAfterNode(node.previousSibling);\n this.__parts.push(part);\n }\n else {\n this.__parts.push(...this.processor.handleAttributeExpressions(node, part.name, part.strings, this.options));\n }\n partIndex++;\n }\n if (dom_1.isCEPolyfill) {\n document.adoptNode(fragment);\n customElements.upgrade(fragment);\n }\n return fragment;\n }\n}\nexports.TemplateInstance = TemplateInstance;\n","\"use strict\";\n/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @module lit-html\n */\nconst dom_1 = require(\"./dom\");\nconst template_1 = require(\"./template\");\n/**\n * The return type of `html`, which holds a Template and the values from\n * interpolated expressions.\n */\nclass TemplateResult {\n constructor(strings, values, type, processor) {\n this.strings = strings;\n this.values = values;\n this.type = type;\n this.processor = processor;\n }\n /**\n * Returns a string of HTML used to create a `