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,KAAK,GAAG,CACjB,C","sources":["webpack://grafana/./public/app/features/live/centrifuge/LiveDataStream.ts","webpack://grafana/./public/app/features/live/centrifuge/channel.ts","webpack://grafana/./public/app/features/live/centrifuge/service.ts","webpack://grafana/./public/app/features/live/centrifuge/transferHandlers.ts","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/centrifuge.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/codes.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/index.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/json.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/subscription.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/transport_http_stream.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/transport_sockjs.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/transport_sse.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/transport_websocket.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/transport_webtransport.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/types.js","webpack://grafana/../../opt/drone/yarncache/centrifuge-npm-3.1.0-9c1dc8c1d8-24bcf02ad8.zip/node_modules/centrifuge/build/utils.js","webpack://grafana/../../opt/drone/yarncache/events-npm-3.3.0-c280bc7e48-f6f487ad21.zip/node_modules/events/events.js","webpack://grafana/../../opt/drone/yarncache/comlink-npm-4.4.1-b05bb2527d-16d58a8f59.zip/node_modules/comlink/dist/esm/comlink.mjs"],"sourcesContent":["import { map, Observable, ReplaySubject, Subject, Subscriber, Subscription } from 'rxjs';\n\nimport {\n DataFrameJSON,\n DataQueryError,\n Field,\n isLiveChannelMessageEvent,\n isLiveChannelStatusEvent,\n LiveChannelConnectionState,\n LiveChannelEvent,\n LiveChannelId,\n LoadingState,\n} from '@grafana/data';\nimport { LiveDataStreamOptions, StreamingFrameAction, StreamingFrameOptions } from '@grafana/runtime/src/services/live';\nimport { toDataQueryError } from '@grafana/runtime/src/utils/toDataQueryError';\n\nimport { getStreamingFrameOptions, StreamingDataFrame } from '../data/StreamingDataFrame';\nimport { StreamingResponseDataType } from '../data/utils';\n\nimport { DataStreamSubscriptionKey, StreamingDataQueryResponse } from './service';\n\nconst bufferIfNot =\n (canEmitObservable: Observable) =>\n (source: Observable): Observable => {\n return new Observable((subscriber: Subscriber) => {\n let buffer: T[] = [];\n let canEmit = true;\n\n const emitBuffer = () => {\n subscriber.next(buffer);\n buffer = [];\n };\n\n const canEmitSub = canEmitObservable.subscribe({\n next: (val) => {\n canEmit = val;\n\n if (canEmit && buffer.length) {\n emitBuffer();\n }\n },\n });\n\n const sourceSub = source.subscribe({\n next(value) {\n if (canEmit) {\n if (!buffer.length) {\n subscriber.next([value]);\n } else {\n emitBuffer();\n }\n } else {\n buffer.push(value);\n }\n },\n error(error) {\n subscriber.error(error);\n },\n complete() {\n subscriber.complete();\n },\n });\n\n return () => {\n sourceSub.unsubscribe();\n canEmitSub.unsubscribe();\n };\n });\n };\n\nexport type DataStreamHandlerDeps = {\n channelId: LiveChannelId;\n liveEventsObservable: Observable>;\n onShutdown: () => void;\n subscriberReadiness: Observable;\n defaultStreamingFrameOptions: Readonly;\n shutdownDelayInMs: number;\n};\n\nenum InternalStreamMessageType {\n Error,\n NewValuesSameSchema,\n ChangedSchema,\n}\n\ntype InternalStreamMessageTypeToData = {\n [InternalStreamMessageType.Error]: {\n error: DataQueryError;\n };\n [InternalStreamMessageType.ChangedSchema]: {};\n [InternalStreamMessageType.NewValuesSameSchema]: {\n values: unknown[][];\n };\n};\n\ntype InternalStreamMessage = T extends InternalStreamMessageType\n ? {\n type: T;\n } & InternalStreamMessageTypeToData[T]\n : never;\n\nconst reduceNewValuesSameSchemaMessages = (\n packets: Array>\n) => ({\n values: packets.reduce((acc, { values }) => {\n for (let i = 0; i < values.length; i++) {\n if (!acc[i]) {\n acc[i] = [];\n }\n for (let j = 0; j < values[i].length; j++) {\n acc[i].push(values[i][j]);\n }\n }\n return acc;\n }, [] as unknown[][]),\n type: InternalStreamMessageType.NewValuesSameSchema,\n});\n\nconst filterMessages = (\n packets: InternalStreamMessage[],\n type: T\n): Array> => packets.filter((p) => p.type === type) as Array>;\n\nexport class LiveDataStream {\n private frameBuffer: StreamingDataFrame;\n private liveEventsSubscription: Subscription;\n private stream: Subject = new ReplaySubject(1);\n private shutdownTimeoutId: ReturnType | undefined;\n\n constructor(private deps: DataStreamHandlerDeps) {\n this.frameBuffer = StreamingDataFrame.empty(deps.defaultStreamingFrameOptions);\n this.liveEventsSubscription = deps.liveEventsObservable.subscribe({\n error: this.onError,\n complete: this.onComplete,\n next: this.onNext,\n });\n }\n\n private shutdown = () => {\n this.stream.complete();\n this.liveEventsSubscription.unsubscribe();\n this.deps.onShutdown();\n };\n\n private shutdownIfNoSubscribers = () => {\n if (!this.stream.observed) {\n this.shutdown();\n }\n };\n\n private onError = (err: any) => {\n console.log('LiveQuery [error]', { err }, this.deps.channelId);\n this.stream.next({\n type: InternalStreamMessageType.Error,\n error: toDataQueryError(err),\n });\n this.shutdown();\n };\n\n private onComplete = () => {\n console.log('LiveQuery [complete]', this.deps.channelId);\n this.shutdown();\n };\n\n private onNext = (evt: LiveChannelEvent) => {\n if (isLiveChannelMessageEvent(evt)) {\n this.process(evt.message);\n return;\n }\n\n const liveChannelStatusEvent = isLiveChannelStatusEvent(evt);\n if (liveChannelStatusEvent && evt.error) {\n this.stream.next({\n type: InternalStreamMessageType.Error,\n error: {\n ...toDataQueryError(evt.error),\n message: `Streaming channel error: ${evt.error.message}`,\n },\n });\n return;\n }\n\n if (\n liveChannelStatusEvent &&\n (evt.state === LiveChannelConnectionState.Connected || evt.state === LiveChannelConnectionState.Pending) &&\n evt.message\n ) {\n this.process(evt.message);\n }\n };\n\n private process = (msg: DataFrameJSON) => {\n const packetInfo = this.frameBuffer.push(msg);\n\n if (packetInfo.schemaChanged) {\n this.stream.next({\n type: InternalStreamMessageType.ChangedSchema,\n });\n } else {\n this.stream.next({\n type: InternalStreamMessageType.NewValuesSameSchema,\n values: this.frameBuffer.getValuesFromLastPacket(),\n });\n }\n };\n\n private resizeBuffer = (bufferOptions: StreamingFrameOptions) => {\n if (bufferOptions && this.frameBuffer.needsResizing(bufferOptions)) {\n this.frameBuffer.resize(bufferOptions);\n }\n };\n\n private prepareInternalStreamForNewSubscription = (options: LiveDataStreamOptions): void => {\n if (!this.frameBuffer.hasAtLeastOnePacket() && options.frame) {\n // will skip initial frames from subsequent subscribers\n this.process(options.frame);\n }\n };\n\n private clearShutdownTimeout = () => {\n if (this.shutdownTimeoutId) {\n clearTimeout(this.shutdownTimeoutId);\n this.shutdownTimeoutId = undefined;\n }\n };\n\n get = (options: LiveDataStreamOptions, subKey: DataStreamSubscriptionKey): Observable => {\n this.clearShutdownTimeout();\n const buffer = getStreamingFrameOptions(options.buffer);\n\n this.resizeBuffer(buffer);\n this.prepareInternalStreamForNewSubscription(options);\n\n const shouldSendLastPacketOnly = options?.buffer?.action === StreamingFrameAction.Replace;\n const fieldsNamesFilter = options.filter?.fields;\n const dataNeedsFiltering = fieldsNamesFilter?.length;\n const fieldFilterPredicate = dataNeedsFiltering ? ({ name }: Field) => fieldsNamesFilter.includes(name) : undefined;\n let matchingFieldIndexes: number[] | undefined = undefined;\n\n const getFullFrameResponseData = (\n messages: InternalStreamMessage[],\n error?: DataQueryError\n ): StreamingDataQueryResponse => {\n matchingFieldIndexes = fieldFilterPredicate\n ? this.frameBuffer.getMatchingFieldIndexes(fieldFilterPredicate)\n : undefined;\n\n if (!shouldSendLastPacketOnly) {\n return {\n key: subKey,\n state: error ? LoadingState.Error : LoadingState.Streaming,\n data: [\n {\n type: StreamingResponseDataType.FullFrame,\n frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer),\n },\n ],\n error,\n };\n }\n\n if (error) {\n // send empty frame with error\n return {\n key: subKey,\n state: LoadingState.Error,\n data: [\n {\n type: StreamingResponseDataType.FullFrame,\n frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, { maxLength: 0 }),\n },\n ],\n error,\n };\n }\n\n if (!messages.length) {\n console.warn(`expected to find at least one non error message ${messages.map(({ type }) => type)}`);\n // send empty frame\n return {\n key: subKey,\n state: LoadingState.Streaming,\n data: [\n {\n type: StreamingResponseDataType.FullFrame,\n frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, { maxLength: 0 }),\n },\n ],\n error,\n };\n }\n\n return {\n key: subKey,\n state: LoadingState.Streaming,\n data: [\n {\n type: StreamingResponseDataType.FullFrame,\n frame: this.frameBuffer.serialize(fieldFilterPredicate, buffer, {\n maxLength: this.frameBuffer.packetInfo.length,\n }),\n },\n ],\n error,\n };\n };\n\n const getNewValuesSameSchemaResponseData = (\n messages: Array>\n ): StreamingDataQueryResponse => {\n const lastMessage = messages.length ? messages[messages.length - 1] : undefined;\n const values =\n shouldSendLastPacketOnly && lastMessage\n ? lastMessage.values\n : reduceNewValuesSameSchemaMessages(messages).values;\n\n const filteredValues = matchingFieldIndexes\n ? values.filter((v, i) => (matchingFieldIndexes as number[]).includes(i))\n : values;\n\n return {\n key: subKey,\n state: LoadingState.Streaming,\n data: [\n {\n type: StreamingResponseDataType.NewValuesSameSchema,\n values: filteredValues,\n },\n ],\n };\n };\n\n let shouldSendFullFrame = true;\n const transformedInternalStream = this.stream.pipe(\n bufferIfNot(this.deps.subscriberReadiness),\n map((messages, i) => {\n const errors = filterMessages(messages, InternalStreamMessageType.Error);\n const lastError = errors.length ? errors[errors.length - 1].error : undefined;\n\n if (shouldSendFullFrame) {\n shouldSendFullFrame = false;\n return getFullFrameResponseData(messages, lastError);\n }\n\n if (errors.length) {\n // send the latest frame with the last error, discard everything else\n return getFullFrameResponseData(messages, lastError);\n }\n\n const schemaChanged = messages.some((n) => n.type === InternalStreamMessageType.ChangedSchema);\n if (schemaChanged) {\n // send the latest frame, discard intermediate appends\n return getFullFrameResponseData(messages, undefined);\n }\n\n const newValueSameSchemaMessages = filterMessages(messages, InternalStreamMessageType.NewValuesSameSchema);\n if (newValueSameSchemaMessages.length !== messages.length) {\n console.warn(`unsupported message type ${messages.map(({ type }) => type)}`);\n }\n\n return getNewValuesSameSchemaResponseData(newValueSameSchemaMessages);\n })\n );\n\n return new Observable((subscriber) => {\n const sub = transformedInternalStream.subscribe({\n next: (n) => {\n subscriber.next(n);\n },\n error: (err) => {\n subscriber.error(err);\n },\n complete: () => {\n subscriber.complete();\n },\n });\n\n return () => {\n // TODO: potentially resize (downsize) the buffer on unsubscribe\n sub.unsubscribe();\n if (!this.stream.observed) {\n this.clearShutdownTimeout();\n this.shutdownTimeoutId = setTimeout(this.shutdownIfNoSubscribers, this.deps.shutdownDelayInMs);\n }\n };\n });\n };\n}\n","import {\n Subscription,\n JoinContext,\n LeaveContext,\n PublicationContext,\n SubscriptionErrorContext,\n SubscribedContext,\n} from 'centrifuge';\nimport { Subject, of, Observable } from 'rxjs';\n\nimport {\n LiveChannelStatusEvent,\n LiveChannelEvent,\n LiveChannelEventType,\n LiveChannelConnectionState,\n LiveChannelPresenceStatus,\n LiveChannelAddress,\n DataFrameJSON,\n isValidLiveChannelAddress,\n} from '@grafana/data';\n\n/**\n * Internal class that maps Centrifuge support to GrafanaLive\n */\nexport class CentrifugeLiveChannel {\n readonly currentStatus: LiveChannelStatusEvent;\n\n readonly opened = Date.now();\n readonly id: string;\n readonly addr: LiveChannelAddress;\n\n readonly stream = new Subject>();\n\n // Hold on to the last header with schema\n lastMessageWithSchema?: DataFrameJSON;\n\n subscription?: Subscription;\n shutdownCallback?: () => void;\n initalized?: boolean;\n\n constructor(id: string, addr: LiveChannelAddress) {\n this.id = id;\n this.addr = addr;\n this.currentStatus = {\n type: LiveChannelEventType.Status,\n id,\n timestamp: this.opened,\n state: LiveChannelConnectionState.Pending,\n };\n if (!isValidLiveChannelAddress(addr)) {\n this.currentStatus.state = LiveChannelConnectionState.Invalid;\n this.currentStatus.error = 'invalid channel address';\n }\n }\n\n // This should only be called when centrifuge is connected\n initalize(): void {\n if (this.initalized) {\n throw new Error('Channel already initalized: ' + this.id);\n }\n this.initalized = true;\n\n this.subscription!.on('publication', (ctx: PublicationContext) => {\n try {\n if (ctx.data) {\n if (ctx.data.schema) {\n this.lastMessageWithSchema = ctx.data as DataFrameJSON;\n }\n\n this.stream.next({\n type: LiveChannelEventType.Message,\n message: ctx.data,\n });\n }\n\n // Clear any error messages\n if (this.currentStatus.error) {\n this.currentStatus.timestamp = Date.now();\n delete this.currentStatus.error;\n this.sendStatus();\n }\n } catch (err) {\n console.log('publish error', this.addr, err);\n this.currentStatus.error = err;\n this.currentStatus.timestamp = Date.now();\n this.sendStatus();\n }\n })\n .on('error', (ctx: SubscriptionErrorContext) => {\n this.currentStatus.timestamp = Date.now();\n this.currentStatus.error = ctx.error.message;\n this.sendStatus();\n })\n .on('subscribed', (ctx: SubscribedContext) => {\n this.currentStatus.timestamp = Date.now();\n this.currentStatus.state = LiveChannelConnectionState.Connected;\n delete this.currentStatus.error;\n\n if (ctx.data?.schema) {\n this.lastMessageWithSchema = ctx.data as DataFrameJSON;\n }\n this.sendStatus(ctx.data);\n })\n .on('unsubscribed', () => {\n this.currentStatus.timestamp = Date.now();\n this.currentStatus.state = LiveChannelConnectionState.Disconnected;\n this.sendStatus();\n })\n .on('subscribing', () => {\n this.currentStatus.timestamp = Date.now();\n this.currentStatus.state = LiveChannelConnectionState.Connecting;\n this.sendStatus();\n })\n .on('join', (ctx: JoinContext) => {\n this.stream.next({ type: LiveChannelEventType.Join, user: ctx.info.user });\n })\n .on('leave', (ctx: LeaveContext) => {\n this.stream.next({ type: LiveChannelEventType.Leave, user: ctx.info.user });\n });\n }\n\n private sendStatus(message?: any) {\n const copy = { ...this.currentStatus };\n if (message) {\n copy.message = message;\n }\n this.stream.next(copy);\n }\n\n disconnectIfNoListeners = () => {\n const count = this.stream.observers.length;\n if (count === 0) {\n this.disconnect();\n }\n };\n\n /**\n * Get the stream of events and\n */\n getStream() {\n return new Observable((subscriber) => {\n const initialMessage = { ...this.currentStatus };\n if (this.lastMessageWithSchema?.schema) {\n // send just schema instead of schema+data to avoid having data gaps\n initialMessage.message = { schema: this.lastMessageWithSchema?.schema };\n }\n\n subscriber.next({ ...this.currentStatus, message: this.lastMessageWithSchema });\n\n const sub = this.stream.subscribe(subscriber);\n return () => {\n sub.unsubscribe();\n const count = this.stream.observers.length;\n\n // Wait 1/4 second to fully disconnect\n if (count === 0) {\n setTimeout(this.disconnectIfNoListeners, 250);\n }\n };\n }) as Observable>;\n }\n\n /**\n * This is configured by the server when the config supports presence\n */\n async getPresence(): Promise {\n if (!this.subscription) {\n return Promise.reject('not subscribed');\n }\n\n return this.subscription!.presence().then((v) => {\n return {\n users: Object.keys(v.clients),\n };\n });\n }\n\n /**\n * This will close and terminate all streams for this channel\n */\n disconnect() {\n this.currentStatus.state = LiveChannelConnectionState.Shutdown;\n this.currentStatus.timestamp = Date.now();\n\n if (this.subscription) {\n this.subscription.unsubscribe();\n this.subscription.removeAllListeners(); // they keep all listeners attached after unsubscribe\n this.subscription = undefined;\n }\n\n this.stream.complete();\n\n this.stream.next({ ...this.currentStatus });\n this.stream.complete();\n\n if (this.shutdownCallback) {\n this.shutdownCallback();\n }\n }\n\n shutdownWithError(err: string) {\n this.currentStatus.error = err;\n this.sendStatus();\n this.disconnect();\n }\n}\n\nexport function getErrorChannel(msg: string, id: string, addr: LiveChannelAddress) {\n return {\n id,\n opened: Date.now(),\n addr,\n\n // return an error\n getStream: () =>\n of({\n type: LiveChannelEventType.Status,\n id,\n timestamp: Date.now(),\n state: LiveChannelConnectionState.Invalid,\n error: msg,\n }),\n\n // already disconnected\n disconnect: () => {},\n };\n}\n","import { Centrifuge, State } from 'centrifuge';\nimport { BehaviorSubject, Observable, share, startWith } from 'rxjs';\n\nimport {\n DataQueryError,\n DataQueryResponse,\n LiveChannelAddress,\n LiveChannelConnectionState,\n LiveChannelId,\n toLiveChannelId,\n} from '@grafana/data';\nimport { FetchResponse } from '@grafana/runtime/src/services/backendSrv';\nimport {\n GrafanaLiveSrv,\n LiveDataStreamOptions,\n LiveQueryDataOptions,\n StreamingFrameAction,\n StreamingFrameOptions,\n} from '@grafana/runtime/src/services/live';\nimport { BackendDataSourceResponse } from '@grafana/runtime/src/utils/queryResponse';\n\nimport { StreamingResponseData } from '../data/utils';\n\nimport { LiveDataStream } from './LiveDataStream';\nimport { CentrifugeLiveChannel } from './channel';\n\nexport type CentrifugeSrvDeps = {\n grafanaAuthToken: string | null;\n appUrl: string;\n orgId: number;\n orgRole: string;\n liveEnabled: boolean;\n dataStreamSubscriberReadiness: Observable;\n};\n\nexport type StreamingDataQueryResponse = Omit & { data: [StreamingResponseData] };\n\nexport type CentrifugeSrv = Omit & {\n getDataStream: (options: LiveDataStreamOptions) => Observable;\n getQueryData: (\n options: LiveQueryDataOptions\n ) => Promise<\n | { data: BackendDataSourceResponse | undefined }\n | FetchResponse\n | DataQueryError\n >;\n};\n\nexport type DataStreamSubscriptionKey = string;\n\nconst defaultStreamingFrameOptions: Readonly = {\n maxLength: 100,\n maxDelta: Infinity,\n action: StreamingFrameAction.Append,\n};\n\nconst dataStreamShutdownDelayInMs = 5000;\n\nexport class CentrifugeService implements CentrifugeSrv {\n readonly open = new Map();\n private readonly liveDataStreamByChannelId: Record = {};\n readonly centrifuge: Centrifuge;\n readonly connectionState: BehaviorSubject;\n readonly connectionBlocker: Promise;\n private readonly dataStreamSubscriberReadiness: Observable;\n\n constructor(private deps: CentrifugeSrvDeps) {\n this.dataStreamSubscriberReadiness = deps.dataStreamSubscriberReadiness.pipe(share(), startWith(true));\n\n let liveUrl = `${deps.appUrl.replace(/^http/, 'ws')}/api/live/ws`;\n\n const token = deps.grafanaAuthToken;\n if (token !== null && token !== '') {\n liveUrl += '?auth_token=' + token;\n }\n\n this.centrifuge = new Centrifuge(liveUrl, {\n timeout: 30000,\n });\n // orgRole is set when logged in *or* anonymous users can use grafana\n if (deps.liveEnabled && deps.orgRole !== '') {\n this.centrifuge.connect(); // do connection\n }\n this.connectionState = new BehaviorSubject(this.centrifuge.state === State.Connected);\n this.connectionBlocker = new Promise((resolve) => {\n if (this.centrifuge.state === State.Connected) {\n return resolve();\n }\n const connectListener = () => {\n resolve();\n this.centrifuge.removeListener('connected', connectListener);\n };\n this.centrifuge.addListener('connected', connectListener);\n });\n\n // Register global listeners\n this.centrifuge.on('connected', this.onConnect);\n this.centrifuge.on('connecting', this.onDisconnect);\n this.centrifuge.on('disconnected', this.onDisconnect);\n this.centrifuge.on('publication', this.onServerSideMessage);\n }\n\n //----------------------------------------------------------\n // Internal functions\n //----------------------------------------------------------\n\n private onConnect = (context: any) => {\n this.connectionState.next(true);\n };\n\n private onDisconnect = (context: any) => {\n this.connectionState.next(false);\n };\n\n private onServerSideMessage = (context: any) => {\n console.log('Publication from server-side channel', context);\n };\n\n /**\n * Get a channel. If the scope, namespace, or path is invalid, a shutdown\n * channel will be returned with an error state indicated in its status\n */\n private getChannel(addr: LiveChannelAddress): CentrifugeLiveChannel {\n const id = `${this.deps.orgId}/${addr.scope}/${addr.namespace}/${addr.path}`;\n let channel = this.open.get(id);\n if (channel != null) {\n return channel;\n }\n\n channel = new CentrifugeLiveChannel(id, addr);\n if (channel.currentStatus.state === LiveChannelConnectionState.Invalid) {\n return channel;\n }\n channel.shutdownCallback = () => {\n this.open.delete(id);\n\n // without a call to `removeSubscription`, the subscription will remain in centrifuge's internal registry\n this.centrifuge.removeSubscription(this.centrifuge.getSubscription(id));\n };\n this.open.set(id, channel);\n\n // Initialize the channel in the background\n this.initChannel(channel).catch((err) => {\n if (channel) {\n channel.currentStatus.state = LiveChannelConnectionState.Invalid;\n channel.shutdownWithError(err);\n }\n this.open.delete(id);\n });\n\n // return the not-yet initialized channel\n return channel;\n }\n\n private async initChannel(channel: CentrifugeLiveChannel): Promise {\n if (this.centrifuge.state !== State.Connected) {\n await this.connectionBlocker;\n }\n const subscription = this.centrifuge.newSubscription(channel.id, {\n data: channel.addr.data,\n });\n channel.subscription = subscription;\n channel.initalize();\n subscription.subscribe();\n return;\n }\n\n //----------------------------------------------------------\n // Exported functions\n //----------------------------------------------------------\n\n /**\n * Listen for changes to the connection state\n */\n getConnectionState = () => {\n return this.connectionState.asObservable();\n };\n\n /**\n * Watch for messages in a channel\n */\n getStream: CentrifugeSrv['getStream'] = (address: LiveChannelAddress) => {\n return this.getChannel(address).getStream();\n };\n\n private createSubscriptionKey = (options: LiveDataStreamOptions): DataStreamSubscriptionKey =>\n options.key ?? `xstr/${streamCounter++}`;\n\n private getLiveDataStream = (options: LiveDataStreamOptions): LiveDataStream => {\n const channelId = toLiveChannelId(options.addr);\n const existingStream = this.liveDataStreamByChannelId[channelId];\n\n if (existingStream) {\n return existingStream;\n }\n\n const channel = this.getChannel(options.addr);\n this.liveDataStreamByChannelId[channelId] = new LiveDataStream({\n channelId,\n onShutdown: () => {\n delete this.liveDataStreamByChannelId[channelId];\n },\n liveEventsObservable: channel.getStream(),\n subscriberReadiness: this.dataStreamSubscriberReadiness,\n defaultStreamingFrameOptions,\n shutdownDelayInMs: dataStreamShutdownDelayInMs,\n });\n return this.liveDataStreamByChannelId[channelId];\n };\n /**\n * Connect to a channel and return results as DataFrames\n */\n getDataStream: CentrifugeSrv['getDataStream'] = (options) => {\n const subscriptionKey = this.createSubscriptionKey(options);\n\n const stream = this.getLiveDataStream(options);\n return stream.get(options, subscriptionKey);\n };\n\n /**\n * Executes a query over the live websocket. Query response can contain live channels we can subscribe to for further updates\n *\n * Since the initial request and subscription are on the same socket, this will support HA setups\n */\n getQueryData: CentrifugeSrv['getQueryData'] = async (options) => {\n if (this.centrifuge.state !== State.Connected) {\n await this.connectionBlocker;\n }\n return this.centrifuge.rpc('grafana.query', options.body);\n };\n\n /**\n * For channels that support presence, this will request the current state from the server.\n *\n * Join and leave messages will be sent to the open stream\n */\n getPresence: CentrifugeSrv['getPresence'] = (address) => {\n return this.getChannel(address).getPresence();\n };\n}\n\n// This is used to give a unique key for each stream. The actual value does not matter\nlet streamCounter = 0;\n","import * as comlink from 'comlink';\nimport { Subscriber } from 'rxjs';\n\n// Observers, ie. functions passed to `observable.subscribe(...)`, are converted to a subclass of `Subscriber` before they are sent to the source Observable.\n// The conversion happens internally in the RxJS library - this transfer handler is catches them and wraps them with a proxy\nconst subscriberTransferHandler: any = {\n canHandle(value: any): boolean {\n return value && value instanceof Subscriber;\n },\n\n serialize(value: Function): [MessagePort, Transferable[]] {\n const obj = comlink.proxy(value);\n\n const { port1, port2 } = new MessageChannel();\n\n comlink.expose(obj, port1);\n\n return [port2, [port2]];\n },\n\n deserialize(value: MessagePort): comlink.Remote {\n value.start();\n\n return comlink.wrap(value);\n },\n};\ncomlink.transferHandlers.set('SubscriberHandler', subscriberTransferHandler);\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Centrifuge = void 0;\nconst subscription_1 = require(\"./subscription\");\nconst codes_1 = require(\"./codes\");\nconst transport_sockjs_1 = require(\"./transport_sockjs\");\nconst transport_websocket_1 = require(\"./transport_websocket\");\nconst transport_http_stream_1 = require(\"./transport_http_stream\");\nconst transport_sse_1 = require(\"./transport_sse\");\nconst transport_webtransport_1 = require(\"./transport_webtransport\");\nconst json_1 = require(\"./json\");\nconst utils_1 = require(\"./utils\");\nconst types_1 = require(\"./types\");\nconst events_1 = __importDefault(require(\"events\"));\nconst defaults = {\n protocol: 'json',\n token: null,\n getToken: null,\n data: null,\n debug: false,\n name: 'js',\n version: '',\n fetch: null,\n readableStream: null,\n websocket: null,\n eventsource: null,\n sockjs: null,\n sockjsOptions: {},\n emulationEndpoint: '/emulation',\n minReconnectDelay: 500,\n maxReconnectDelay: 20000,\n timeout: 5000,\n maxServerPingDelay: 10000,\n networkEventTarget: null,\n};\n/** Centrifuge is a Centrifuge/Centrifugo bidirectional client. */\nclass Centrifuge extends events_1.default {\n /** Constructs Centrifuge client. Call connect() method to start connecting. */\n constructor(endpoint, options) {\n super();\n this._reconnectTimeout = null;\n this._refreshTimeout = null;\n this._serverPingTimeout = null;\n this.state = types_1.State.Disconnected;\n this._endpoint = endpoint;\n this._emulation = false;\n this._transports = [];\n this._currentTransportIndex = 0;\n this._triedAllTransports = false;\n this._transportWasOpen = false;\n this._transport = null;\n this._transportClosed = true;\n this._encoder = null;\n this._decoder = null;\n this._reconnecting = false;\n this._reconnectTimeout = null;\n this._reconnectAttempts = 0;\n this._client = null;\n this._session = '';\n this._node = '';\n this._subs = {};\n this._serverSubs = {};\n this._commandId = 0;\n this._commands = [];\n this._batching = false;\n this._refreshRequired = false;\n this._refreshTimeout = null;\n this._callbacks = {};\n this._token = undefined;\n this._dispatchPromise = Promise.resolve();\n this._serverPing = 0;\n this._serverPingTimeout = null;\n this._sendPong = false;\n this._promises = {};\n this._promiseId = 0;\n this._debugEnabled = false;\n this._config = Object.assign(Object.assign({}, defaults), options);\n this._configure();\n if (this._debugEnabled) {\n this.on('state', (ctx) => {\n this._debug('client state', ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n this._debug('client error', ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** newSubscription allocates new Subscription to a channel. Since server only allows\n * one subscription per channel per client this method throws if client already has\n * channel subscription in internal registry.\n * */\n newSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new subscription_1.Subscription(this, channel, options);\n this._subs[channel] = sub;\n return sub;\n }\n /** getSubscription returns Subscription if it's registered in the internal\n * registry or null. */\n getSubscription(channel) {\n return this._getSub(channel);\n }\n /** removeSubscription allows removing Subcription from the internal registry. Subscrption\n * must be in unsubscribed state. */\n removeSubscription(sub) {\n if (!sub) {\n return;\n }\n if (sub.state !== types_1.SubscriptionState.Unsubscribed) {\n sub.unsubscribe();\n }\n this._removeSubscription(sub);\n }\n /** Get a map with all current client-side subscriptions. */\n subscriptions() {\n return this._subs;\n }\n /** ready returns a Promise which resolves upon client goes to Connected\n * state and rejects in case of client goes to Disconnected or Failed state.\n * Users can provide optional timeout in milliseconds. */\n ready(timeout) {\n if (this.state === types_1.State.Disconnected) {\n return Promise.reject({ code: codes_1.errorCodes.clientDisconnected, message: 'client disconnected' });\n }\n if (this.state === types_1.State.Connected) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const ctx = {\n resolve: res,\n reject: rej\n };\n if (timeout) {\n ctx.timeout = setTimeout(function () {\n rej({ code: codes_1.errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[this._nextPromiseId()] = ctx;\n });\n }\n /** connect to a server. */\n connect() {\n if (this._isConnected()) {\n this._debug('connect called when already connected');\n return;\n }\n if (this._isConnecting()) {\n this._debug('connect called when already connecting');\n return;\n }\n this._reconnectAttempts = 0;\n this._startConnecting();\n }\n /** disconnect from a server. */\n disconnect() {\n this._disconnect(codes_1.disconnectedCodes.disconnectCalled, 'disconnect called', false);\n }\n /** send asynchronous data to a server (without any response from a server\n * expected, see rpc method if you need response). */\n send(data) {\n const cmd = {\n send: {\n data: data\n }\n };\n const self = this;\n return this._methodCall().then(function () {\n const sent = self._transportSendCommands([cmd]); // can send message to server without id set\n if (!sent) {\n return Promise.reject(self._createErrorObject(codes_1.errorCodes.transportWriteError, 'transport write error'));\n }\n return Promise.resolve();\n });\n }\n /** rpc to a server - i.e. a call which waits for a response with data. */\n rpc(method, data) {\n const cmd = {\n rpc: {\n method: method,\n data: data\n }\n };\n const self = this;\n return this._methodCall().then(function () {\n return self._callPromise(cmd, function (reply) {\n return {\n 'data': reply.rpc.data\n };\n });\n });\n }\n /** publish data to a channel. */\n publish(channel, data) {\n const cmd = {\n publish: {\n channel: channel,\n data: data\n }\n };\n const self = this;\n return this._methodCall().then(function () {\n return self._callPromise(cmd, function () {\n return {};\n });\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) – provide an explicit limit > 0 to load publications.*/\n history(channel, options) {\n const cmd = {\n history: this._getHistoryRequest(channel, options)\n };\n const self = this;\n return this._methodCall().then(function () {\n return self._callPromise(cmd, function (reply) {\n const result = reply.history;\n const publications = [];\n if (result.publications) {\n for (let i = 0; i < result.publications.length; i++) {\n publications.push(self._getPublicationContext(channel, result.publications[i]));\n }\n }\n return {\n 'publications': publications,\n 'epoch': result.epoch || '',\n 'offset': result.offset || 0\n };\n });\n });\n }\n /** presence for a channel. */\n presence(channel) {\n const cmd = {\n presence: {\n channel: channel\n }\n };\n const self = this;\n return this._methodCall().then(function () {\n return self._callPromise(cmd, function (reply) {\n return {\n 'clients': reply.presence.presence\n };\n });\n });\n }\n /** presence stats for a channel. */\n presenceStats(channel) {\n const cmd = {\n 'presence_stats': {\n channel: channel\n }\n };\n const self = this;\n return this._methodCall().then(function () {\n return self._callPromise(cmd, function (reply) {\n const result = reply.presence_stats;\n return {\n 'numUsers': result.num_users,\n 'numClients': result.num_clients\n };\n });\n });\n }\n /** start command batching (collect into temporary buffer without sending to a server)\n * until stopBatching called.*/\n startBatching() {\n // start collecting messages without sending them to Centrifuge until flush\n // method called\n this._batching = true;\n }\n /** stop batching commands and flush collected commands to the\n * network (all in one request/frame).*/\n stopBatching() {\n const self = this;\n // Why so nested? Two levels here requred to deal with promise resolving queue.\n // In Subscription case we wait 2 futures before sending data to connection.\n // Otherwise _batching becomes false before batching decision has a chance to be executed.\n Promise.resolve().then(function () {\n Promise.resolve().then(function () {\n self._batching = false;\n self._flush();\n });\n });\n }\n _debug(...args) {\n if (!this._debugEnabled) {\n return;\n }\n (0, utils_1.log)('debug', args);\n }\n /** @internal */\n _setFormat(format) {\n if (this._formatOverride(format)) {\n return;\n }\n if (format === 'protobuf') {\n throw new Error('not implemented by JSON-only Centrifuge client, use client with Protobuf support');\n }\n this._encoder = new json_1.JsonEncoder();\n this._decoder = new json_1.JsonDecoder();\n }\n /** @internal */\n _formatOverride(_format) {\n return false;\n }\n _configure() {\n if (!('Promise' in globalThis)) {\n throw new Error('Promise polyfill required');\n }\n if (!this._endpoint) {\n throw new Error('endpoint configuration required');\n }\n if (this._config.protocol !== 'json' && this._config.protocol !== 'protobuf') {\n throw new Error('unsupported protocol ' + this._config.protocol);\n }\n if (this._config.token !== null) {\n this._token = this._config.token;\n }\n this._setFormat('json');\n if (this._config.protocol === 'protobuf') {\n this._setFormat('protobuf');\n }\n if (this._config.debug === true ||\n (typeof localStorage !== 'undefined' && localStorage.getItem('centrifuge.debug'))) {\n this._debugEnabled = true;\n }\n this._debug('config', this._config);\n if (typeof this._endpoint === 'string') {\n // Single address.\n }\n else if (typeof this._endpoint === 'object' && this._endpoint instanceof Array) {\n this._transports = this._endpoint;\n this._emulation = true;\n for (const i in this._transports) {\n const transportConfig = this._transports[i];\n if (!transportConfig.endpoint || !transportConfig.transport) {\n throw new Error('malformed transport configuration');\n }\n const transportName = transportConfig.transport;\n if (['websocket', 'http_stream', 'sse', 'sockjs', 'webtransport'].indexOf(transportName) < 0) {\n throw new Error('unsupported transport name: ' + transportName);\n }\n }\n }\n else {\n throw new Error('unsupported url configuration type: only string or array of objects are supported');\n }\n }\n _setState(newState) {\n if (this.state !== newState) {\n this._reconnecting = false;\n const oldState = this.state;\n this.state = newState;\n this.emit('state', { newState, oldState });\n return true;\n }\n return false;\n }\n _isDisconnected() {\n return this.state === types_1.State.Disconnected;\n }\n _isConnecting() {\n return this.state === types_1.State.Connecting;\n }\n _isConnected() {\n return this.state === types_1.State.Connected;\n }\n _nextCommandId() {\n return ++this._commandId;\n }\n _setNetworkEvents() {\n let eventTarget = null;\n if (this._config.networkEventTarget !== null) {\n eventTarget = this._config.networkEventTarget;\n }\n else if (typeof globalThis.addEventListener !== 'undefined') {\n eventTarget = globalThis;\n }\n if (eventTarget) {\n eventTarget.addEventListener('offline', () => {\n this._debug('offline event triggered');\n if (this.state === types_1.State.Connected && this._transport && !this._transportClosed) {\n this._transportClosed = true;\n this._transport.close();\n }\n });\n eventTarget.addEventListener('online', () => {\n this._debug('online event triggered');\n if (this.state === types_1.State.Connecting) {\n this._clearReconnectTimeout();\n this._startReconnecting();\n }\n });\n }\n }\n _getReconnectDelay() {\n const delay = (0, utils_1.backoff)(this._reconnectAttempts, this._config.minReconnectDelay, this._config.maxReconnectDelay);\n this._reconnectAttempts += 1;\n return delay;\n }\n _clearOutgoingRequests() {\n // fire errbacks of registered outgoing calls.\n for (const id in this._callbacks) {\n if (this._callbacks.hasOwnProperty(id)) {\n const callbacks = this._callbacks[id];\n clearTimeout(callbacks.timeout);\n const errback = callbacks.errback;\n if (!errback) {\n continue;\n }\n errback({ error: this._createErrorObject(codes_1.errorCodes.connectionClosed, 'connection closed') });\n }\n }\n this._callbacks = {};\n }\n _clearConnectedState() {\n this._client = null;\n this._clearServerPingTimeout();\n this._clearRefreshTimeout();\n // fire events for client-side subscriptions.\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n if (sub.state === types_1.SubscriptionState.Subscribed) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(codes_1.subscribingCodes.transportClosed, 'transport closed');\n }\n }\n // fire events for server-side subscriptions.\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel)) {\n this.emit('subscribing', { channel: channel });\n }\n }\n }\n _handleWriteError(commands) {\n for (const command of commands) {\n const id = command.id;\n if (!(id in this._callbacks)) {\n continue;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n const errback = callbacks.errback;\n errback({ error: this._createErrorObject(codes_1.errorCodes.transportWriteError, 'transport write error') });\n }\n }\n _transportSendCommands(commands) {\n if (!commands.length) {\n return true;\n }\n if (!this._transport) {\n return false;\n }\n try {\n this._transport.send(this._encoder.encodeCommands(commands), this._session, this._node);\n }\n catch (e) {\n this._debug('error writing commands', e);\n this._handleWriteError(commands);\n return false;\n }\n return true;\n }\n _initializeTransport() {\n let websocket;\n if (this._config.websocket !== null) {\n websocket = this._config.websocket;\n }\n else {\n if (!(typeof globalThis.WebSocket !== 'function' && typeof globalThis.WebSocket !== 'object')) {\n websocket = globalThis.WebSocket;\n }\n }\n let sockjs = null;\n if (this._config.sockjs !== null) {\n sockjs = this._config.sockjs;\n }\n else {\n if (typeof globalThis.SockJS !== 'undefined') {\n sockjs = globalThis.SockJS;\n }\n }\n let eventsource = null;\n if (this._config.eventsource !== null) {\n eventsource = this._config.eventsource;\n }\n else {\n if (typeof globalThis.EventSource !== 'undefined') {\n eventsource = globalThis.EventSource;\n }\n }\n let fetchFunc = null;\n if (this._config.fetch !== null) {\n fetchFunc = this._config.fetch;\n }\n else {\n if (typeof globalThis.fetch !== 'undefined') {\n fetchFunc = globalThis.fetch;\n }\n }\n let readableStream = null;\n if (this._config.readableStream !== null) {\n readableStream = this._config.readableStream;\n }\n else {\n if (typeof globalThis.ReadableStream !== 'undefined') {\n readableStream = globalThis.ReadableStream;\n }\n }\n if (!this._emulation) {\n if ((0, utils_1.startsWith)(this._endpoint, 'http')) {\n throw new Error('Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport');\n }\n else {\n this._debug('client will use websocket');\n this._transport = new transport_websocket_1.WebsocketTransport(this._endpoint, {\n websocket: websocket\n });\n if (!this._transport.supported()) {\n throw new Error('WebSocket not available');\n }\n }\n }\n else {\n if (this._currentTransportIndex >= this._transports.length) {\n this._triedAllTransports = true;\n this._currentTransportIndex = 0;\n }\n let count = 0;\n while (true) {\n if (count >= this._transports.length) {\n throw new Error('no supported transport found');\n }\n const transportConfig = this._transports[this._currentTransportIndex];\n const transportName = transportConfig.transport;\n const transportEndpoint = transportConfig.endpoint;\n if (transportName === 'websocket') {\n this._debug('trying websocket transport');\n this._transport = new transport_websocket_1.WebsocketTransport(transportEndpoint, {\n websocket: websocket\n });\n if (!this._transport.supported()) {\n this._debug('websocket transport not available');\n this._currentTransportIndex++;\n count++;\n continue;\n }\n }\n else if (transportName === 'webtransport') {\n this._debug('trying webtransport transport');\n this._transport = new transport_webtransport_1.WebtransportTransport(transportEndpoint, {\n webtransport: globalThis.WebTransport,\n decoder: this._decoder,\n encoder: this._encoder\n });\n if (!this._transport.supported()) {\n this._debug('webtransport transport not available');\n this._currentTransportIndex++;\n count++;\n continue;\n }\n }\n else if (transportName === 'http_stream') {\n this._debug('trying http_stream transport');\n this._transport = new transport_http_stream_1.HttpStreamTransport(transportEndpoint, {\n fetch: fetchFunc,\n readableStream: readableStream,\n emulationEndpoint: this._config.emulationEndpoint,\n decoder: this._decoder,\n encoder: this._encoder\n });\n if (!this._transport.supported()) {\n this._debug('http_stream transport not available');\n this._currentTransportIndex++;\n count++;\n continue;\n }\n }\n else if (transportName === 'sse') {\n this._debug('trying sse transport');\n this._transport = new transport_sse_1.SseTransport(transportEndpoint, {\n eventsource: eventsource,\n fetch: fetchFunc,\n emulationEndpoint: this._config.emulationEndpoint,\n });\n if (!this._transport.supported()) {\n this._debug('sse transport not available');\n this._currentTransportIndex++;\n count++;\n continue;\n }\n }\n else if (transportName === 'sockjs') {\n this._debug('trying sockjs');\n this._transport = new transport_sockjs_1.SockjsTransport(transportEndpoint, {\n sockjs: sockjs,\n sockjsOptions: this._config.sockjsOptions\n });\n if (!this._transport.supported()) {\n this._debug('sockjs transport not available');\n this._currentTransportIndex++;\n count++;\n continue;\n }\n }\n else {\n throw new Error('unknown transport ' + transportName);\n }\n break;\n }\n }\n const self = this;\n let transportName;\n let wasOpen = false;\n let optimistic = true;\n if (this._transport.name() === 'sse') {\n // Avoid using optimistic subscriptions with SSE/EventSource as we are sending\n // initial data in URL params. URL is recommended to be 2048 chars max – so adding\n // subscription data may be risky.\n optimistic = false;\n }\n const initialCommands = [];\n if (this._transport.emulation()) {\n const connectCommand = self._sendConnect(true);\n initialCommands.push(connectCommand);\n if (optimistic) {\n const subscribeCommands = self._sendSubscribeCommands(true, true);\n for (const i in subscribeCommands) {\n initialCommands.push(subscribeCommands[i]);\n }\n }\n }\n const initialData = this._encoder.encodeCommands(initialCommands);\n this._transport.initialize(this._config.protocol, {\n onOpen: function () {\n wasOpen = true;\n transportName = self._transport.subName();\n self._debug(transportName, 'transport open');\n self._transportWasOpen = true;\n self._transportClosed = false;\n if (self._transport.emulation()) {\n return;\n }\n self.startBatching();\n self._sendConnect(false);\n if (optimistic) {\n self._sendSubscribeCommands(true, false);\n }\n self.stopBatching();\n },\n onError: function (e) {\n self._debug('transport level error', e);\n },\n onClose: function (closeEvent) {\n self._debug(self._transport.name(), 'transport closed');\n self._transportClosed = true;\n let reason = 'connection closed';\n let needReconnect = true;\n let code = 0;\n if (closeEvent && 'code' in closeEvent && closeEvent.code) {\n code = closeEvent.code;\n }\n if (closeEvent && closeEvent.reason) {\n try {\n const advice = JSON.parse(closeEvent.reason);\n reason = advice.reason;\n needReconnect = advice.reconnect;\n }\n catch (e) {\n reason = closeEvent.reason;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n needReconnect = false;\n }\n }\n }\n if (code < 3000) {\n if (code === 1009) {\n code = codes_1.disconnectedCodes.messageSizeLimit;\n reason = 'message size limit exceeded';\n needReconnect = false;\n }\n else {\n code = codes_1.connectingCodes.transportClosed;\n reason = 'transport closed';\n }\n if (self._emulation && !self._transportWasOpen) {\n self._currentTransportIndex++;\n if (self._currentTransportIndex >= self._transports.length) {\n self._triedAllTransports = true;\n self._currentTransportIndex = 0;\n }\n }\n }\n else {\n // Codes >= 3000 are sent from a server application level.\n self._transportWasOpen = true;\n }\n let isInitialHandshake = false;\n if (self._emulation && !self._transportWasOpen && !self._triedAllTransports) {\n isInitialHandshake = true;\n }\n if (self._isConnecting() && !wasOpen) {\n self.emit('error', {\n type: 'transport',\n error: {\n code: codes_1.errorCodes.transportClosed,\n message: 'transport closed'\n },\n transport: self._transport.name()\n });\n }\n self._disconnect(code, reason, needReconnect);\n if (self._isConnecting()) {\n let delay = self._getReconnectDelay();\n if (isInitialHandshake) {\n delay = 0;\n }\n self._debug('reconnect after ' + delay + ' milliseconds');\n self._reconnecting = false;\n self._reconnectTimeout = setTimeout(() => {\n self._startReconnecting();\n }, delay);\n }\n },\n onMessage: function (data) {\n self._dataReceived(data);\n }\n }, initialData);\n }\n _sendConnect(skipSending) {\n const connectCommand = this._constructConnectCommand();\n const self = this;\n this._call(connectCommand, skipSending).then(resolveCtx => {\n // @ts-ignore = improve later.\n const result = resolveCtx.reply.connect;\n self._connectResponse(result);\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._connectError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n return connectCommand;\n }\n _startReconnecting() {\n if (!this._isConnecting() || this._reconnecting) {\n return;\n }\n this._reconnecting = true;\n const needTokenRefresh = this._refreshRequired || (!this._token && this._config.getToken !== null);\n if (!needTokenRefresh) {\n this._initializeTransport();\n return;\n }\n const self = this;\n this._getToken().then(function (token) {\n if (!self._isConnecting()) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n self._initializeTransport();\n }).catch(function (e) {\n if (!self._isConnecting()) {\n return;\n }\n self.emit('error', {\n 'type': 'connectToken',\n 'error': {\n code: codes_1.errorCodes.clientConnectToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n const delay = self._getReconnectDelay();\n self._debug('error on connection token refresh, reconnect after ' + delay + ' milliseconds', e);\n self._reconnecting = false;\n self._reconnectTimeout = setTimeout(() => {\n self._startReconnecting();\n }, delay);\n });\n }\n _connectError(err) {\n if (this.state !== types_1.State.Connecting) {\n return;\n }\n if (err.code === 109) { // token expired.\n // next connect attempt will try to refresh token.\n this._refreshRequired = true;\n }\n if (err.code < 100 || err.temporary === true || err.code === 109) {\n this.emit('error', {\n 'type': 'connect',\n 'error': err\n });\n // Not yet connected, closing transport is enough.\n if (this._transport && !this._transportClosed) {\n this._transportClosed = true;\n this._transport.close();\n }\n }\n else {\n this._disconnect(err.code, err.message, false);\n }\n }\n _constructConnectCommand() {\n const req = {};\n if (this._token) {\n req.token = this._token;\n }\n if (this._config.data) {\n req.data = this._config.data;\n }\n if (this._config.name) {\n req.name = this._config.name;\n }\n if (this._config.version) {\n req.version = this._config.version;\n }\n const subs = {};\n let hasSubs = false;\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].recoverable) {\n hasSubs = true;\n const sub = {\n 'recover': true\n };\n if (this._serverSubs[channel].offset) {\n sub['offset'] = this._serverSubs[channel].offset;\n }\n if (this._serverSubs[channel].epoch) {\n sub['epoch'] = this._serverSubs[channel].epoch;\n }\n subs[channel] = sub;\n }\n }\n if (hasSubs) {\n req.subs = subs;\n }\n return {\n connect: req\n };\n }\n _getHistoryRequest(channel, options) {\n const req = {\n channel: channel\n };\n if (options !== undefined) {\n if (options.since) {\n req.since = {\n offset: options.since.offset\n };\n if (options.since.epoch) {\n req.since.epoch = options.since.epoch;\n }\n }\n if (options.limit !== undefined) {\n req.limit = options.limit;\n }\n if (options.reverse === true) {\n req.reverse = true;\n }\n }\n return req;\n }\n _methodCall() {\n if (this._isConnected()) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const timeout = setTimeout(function () {\n rej({ code: codes_1.errorCodes.timeout, message: 'timeout' });\n }, this._config.timeout);\n this._promises[this._nextPromiseId()] = {\n timeout: timeout,\n resolve: res,\n reject: rej\n };\n });\n }\n _callPromise(cmd, resultCB) {\n return new Promise((resolve, reject) => {\n this._call(cmd, false).then(resolveCtx => {\n // @ts-ignore - improve later.\n resolve(resultCB(resolveCtx.reply));\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n reject(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n });\n }\n _dataReceived(data) {\n if (this._serverPing > 0) {\n this._waitServerPing();\n }\n const replies = this._decoder.decodeReplies(data);\n // We have to guarantee order of events in replies processing - i.e. start processing\n // next reply only when we finished processing of current one. Without syncing things in\n // this way we could get wrong publication events order as reply promises resolve\n // on next loop tick so for loop continues before we finished emitting all reply events.\n this._dispatchPromise = this._dispatchPromise.then(() => {\n let finishDispatch;\n this._dispatchPromise = new Promise(resolve => {\n finishDispatch = resolve;\n });\n this._dispatchSynchronized(replies, finishDispatch);\n });\n }\n _dispatchSynchronized(replies, finishDispatch) {\n let p = Promise.resolve();\n for (const i in replies) {\n if (replies.hasOwnProperty(i)) {\n p = p.then(() => {\n return this._dispatchReply(replies[i]);\n });\n }\n }\n p = p.then(() => {\n finishDispatch();\n });\n }\n _dispatchReply(reply) {\n let next;\n const p = new Promise(resolve => {\n next = resolve;\n });\n if (reply === undefined || reply === null) {\n this._debug('dispatch: got undefined or null reply');\n next();\n return p;\n }\n const id = reply.id;\n if (id && id > 0) {\n this._handleReply(reply, next);\n }\n else {\n if (!reply.push) {\n this._handleServerPing(next);\n }\n else {\n this._handlePush(reply.push, next);\n }\n }\n return p;\n }\n _call(cmd, skipSending) {\n return new Promise((resolve, reject) => {\n cmd.id = this._nextCommandId();\n this._registerCall(cmd.id, resolve, reject);\n if (!skipSending) {\n this._addCommand(cmd);\n }\n });\n }\n _startConnecting() {\n this._debug('start connecting');\n if (this._setState(types_1.State.Connecting)) {\n this.emit('connecting', { code: codes_1.connectingCodes.connectCalled, reason: 'connect called' });\n }\n this._client = null;\n this._startReconnecting();\n }\n _disconnect(code, reason, reconnect) {\n if (this._isDisconnected()) {\n return;\n }\n const previousState = this.state;\n const ctx = {\n code: code,\n reason: reason\n };\n let needEvent = false;\n if (reconnect) {\n needEvent = this._setState(types_1.State.Connecting);\n }\n else {\n needEvent = this._setState(types_1.State.Disconnected);\n this._rejectPromises({ code: codes_1.errorCodes.clientDisconnected, message: 'disconnected' });\n }\n this._clearOutgoingRequests();\n if (previousState === types_1.State.Connecting) {\n this._clearReconnectTimeout();\n }\n if (previousState === types_1.State.Connected) {\n this._clearConnectedState();\n }\n if (needEvent) {\n if (this._isConnecting()) {\n this.emit('connecting', ctx);\n }\n else {\n this.emit('disconnected', ctx);\n }\n }\n if (this._transport && !this._transportClosed) {\n this._transportClosed = true;\n this._transport.close();\n }\n }\n _failUnauthorized() {\n this._disconnect(codes_1.disconnectedCodes.unauthorized, 'unauthorized', false);\n }\n _getToken() {\n this._debug('get connection token');\n if (!this._config.getToken) {\n throw new Error('provide a function to get connection token');\n }\n return this._config.getToken({});\n }\n _refresh() {\n const clientId = this._client;\n const self = this;\n this._getToken().then(function (token) {\n if (clientId !== self._client) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n if (!self._isConnected()) {\n return;\n }\n const cmd = {\n refresh: { token: self._token }\n };\n self._call(cmd, false).then(resolveCtx => {\n // @ts-ignore - improve later.\n const result = resolveCtx.reply.refresh;\n self._refreshResponse(result);\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._refreshError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }).catch(function (e) {\n self.emit('error', {\n type: 'refreshToken',\n error: {\n code: codes_1.errorCodes.clientRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n }\n _refreshError(err) {\n if (err.code < 100 || err.temporary === true) {\n this.emit('error', {\n type: 'refresh',\n error: err\n });\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n }\n else {\n this._disconnect(err.code, err.message, false);\n }\n }\n _getRefreshRetryDelay() {\n return (0, utils_1.backoff)(0, 5000, 10000);\n }\n _refreshResponse(result) {\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n if (result.expires) {\n this._client = result.client;\n this._refreshTimeout = setTimeout(() => this._refresh(), (0, utils_1.ttlMilliseconds)(result.ttl));\n }\n }\n _removeSubscription(sub) {\n if (sub === null) {\n return;\n }\n delete this._subs[sub.channel];\n }\n _unsubscribe(sub) {\n if (!this._isConnected()) {\n return;\n }\n const req = {\n channel: sub.channel\n };\n const cmd = { unsubscribe: req };\n const self = this;\n this._call(cmd, false).then(resolveCtx => {\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n self._disconnect(codes_1.connectingCodes.unsubscribeError, 'unsubscribe error', true);\n });\n }\n _getSub(channel) {\n const sub = this._subs[channel];\n if (!sub) {\n return null;\n }\n return sub;\n }\n _isServerSub(channel) {\n return this._serverSubs[channel] !== undefined;\n }\n _sendSubscribeCommands(optimistic, skipSending) {\n const commands = [];\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n if (sub._inflight === true) {\n continue;\n }\n if (sub.state === types_1.SubscriptionState.Subscribing) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n const cmd = sub._subscribe(optimistic, skipSending);\n if (cmd) {\n commands.push(cmd);\n }\n }\n }\n return commands;\n }\n _connectResponse(result) {\n this._transportWasOpen = true;\n this._reconnectAttempts = 0;\n this._refreshRequired = false;\n if (this._isConnected()) {\n return;\n }\n this._client = result.client;\n this._setState(types_1.State.Connected);\n this._setNetworkEvents();\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n }\n if (result.expires) {\n this._refreshTimeout = setTimeout(() => this._refresh(), (0, utils_1.ttlMilliseconds)(result.ttl));\n }\n this._session = result.session;\n this._node = result.node;\n this.startBatching();\n this._sendSubscribeCommands(false, false);\n this.stopBatching();\n const ctx = {\n client: result.client,\n transport: this._transport.subName()\n };\n if (result.data) {\n ctx.data = result.data;\n }\n this.emit('connected', ctx);\n this._resolvePromises();\n this._processServerSubs(result.subs || {});\n if (result.ping && result.ping > 0) {\n this._serverPing = result.ping * 1000;\n this._sendPong = result.pong === true;\n this._waitServerPing();\n }\n else {\n this._serverPing = 0;\n }\n }\n _processServerSubs(subs) {\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = subs[channel];\n this._serverSubs[channel] = {\n 'offset': sub.offset,\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false\n };\n const subCtx = this._getSubscribeContext(channel, sub);\n this.emit('subscribed', subCtx);\n }\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = subs[channel];\n if (sub.recovered) {\n const pubs = sub.publications;\n if (pubs && pubs.length > 0) {\n for (const i in pubs) {\n if (pubs.hasOwnProperty(i)) {\n this._handlePublication(channel, pubs[i]);\n }\n }\n }\n }\n }\n for (const channel in this._serverSubs) {\n if (!this._serverSubs.hasOwnProperty(channel)) {\n continue;\n }\n if (!subs[channel]) {\n this.emit('unsubscribed', { channel: channel });\n delete this._serverSubs[channel];\n }\n }\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearReconnectTimeout() {\n if (this._reconnectTimeout !== null) {\n clearTimeout(this._reconnectTimeout);\n this._reconnectTimeout = null;\n }\n }\n _clearServerPingTimeout() {\n if (this._serverPingTimeout !== null) {\n clearTimeout(this._serverPingTimeout);\n this._serverPingTimeout = null;\n }\n }\n _waitServerPing() {\n if (this._config.maxServerPingDelay === 0) {\n return;\n }\n if (!this._isConnected()) {\n return;\n }\n this._clearServerPingTimeout();\n this._serverPingTimeout = setTimeout(() => {\n if (!this._isConnected()) {\n return;\n }\n this._disconnect(codes_1.connectingCodes.noPing, 'no ping', true);\n }, this._serverPing + this._config.maxServerPingDelay);\n }\n _getSubscribeContext(channel, result) {\n const ctx = {\n channel: channel,\n positioned: false,\n recoverable: false,\n wasRecovering: false,\n recovered: false\n };\n if (result.recovered) {\n ctx.recovered = true;\n }\n if (result.positioned) {\n ctx.positioned = true;\n }\n if (result.recoverable) {\n ctx.recoverable = true;\n }\n if (result.was_recovering) {\n ctx.wasRecovering = true;\n }\n let epoch = '';\n if ('epoch' in result) {\n epoch = result.epoch;\n }\n let offset = 0;\n if ('offset' in result) {\n offset = result.offset;\n }\n if (ctx.positioned || ctx.recoverable) {\n ctx.streamPosition = {\n 'offset': offset,\n 'epoch': epoch\n };\n }\n if (result.data) {\n ctx.data = result.data;\n }\n return ctx;\n }\n _handleReply(reply, next) {\n const id = reply.id;\n if (!(id in this._callbacks)) {\n next();\n return;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n if (!(0, utils_1.errorExists)(reply)) {\n const callback = callbacks.callback;\n if (!callback) {\n return;\n }\n callback({ reply, next });\n }\n else {\n const errback = callbacks.errback;\n if (!errback) {\n next();\n return;\n }\n const error = reply.error;\n errback({ error, next });\n }\n }\n _handleJoin(channel, join) {\n const sub = this._getSub(channel);\n if (!sub) {\n if (this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(join.info) };\n this.emit('join', ctx);\n }\n return;\n }\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._handleJoin(join);\n }\n _handleLeave(channel, leave) {\n const sub = this._getSub(channel);\n if (!sub) {\n if (this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(leave.info) };\n this.emit('leave', ctx);\n }\n return;\n }\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._handleLeave(leave);\n }\n _handleUnsubscribe(channel, unsubscribe) {\n const sub = this._getSub(channel);\n if (!sub) {\n if (this._isServerSub(channel)) {\n delete this._serverSubs[channel];\n this.emit('unsubscribed', { channel: channel });\n }\n return;\n }\n if (unsubscribe.code < 2500) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._setUnsubscribed(unsubscribe.code, unsubscribe.reason, false);\n }\n else {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(unsubscribe.code, unsubscribe.reason);\n }\n }\n _handleSubscribe(channel, sub) {\n this._serverSubs[channel] = {\n 'offset': sub.offset,\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false\n };\n this.emit('subscribed', this._getSubscribeContext(channel, sub));\n }\n _handleDisconnect(disconnect) {\n const code = disconnect.code;\n let reconnect = true;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n reconnect = false;\n }\n this._disconnect(code, disconnect.reason, reconnect);\n }\n _getPublicationContext(channel, pub) {\n const ctx = {\n channel: channel,\n data: pub.data\n };\n if (pub.offset) {\n ctx.offset = pub.offset;\n }\n if (pub.info) {\n ctx.info = this._getJoinLeaveContext(pub.info);\n }\n if (pub.tags) {\n ctx.tags = pub.tags;\n }\n return ctx;\n }\n _getJoinLeaveContext(clientInfo) {\n const info = {\n client: clientInfo.client,\n user: clientInfo.user\n };\n if (clientInfo.conn_info) {\n info.connInfo = clientInfo.conn_info;\n }\n if (clientInfo.chan_info) {\n info.chanInfo = clientInfo.chan_info;\n }\n return info;\n }\n _handlePublication(channel, pub) {\n const sub = this._getSub(channel);\n if (!sub) {\n if (this._isServerSub(channel)) {\n const ctx = this._getPublicationContext(channel, pub);\n this.emit('publication', ctx);\n if (pub.offset !== undefined) {\n this._serverSubs[channel].offset = pub.offset;\n }\n }\n return;\n }\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n sub._handlePublication(pub);\n }\n _handleMessage(message) {\n this.emit('message', { data: message.data });\n }\n _handleServerPing(next) {\n if (this._sendPong) {\n const cmd = {};\n this._transportSendCommands([cmd]);\n }\n next();\n }\n _handlePush(data, next) {\n const channel = data.channel;\n if (data.pub) {\n this._handlePublication(channel, data.pub);\n }\n else if (data.message) {\n this._handleMessage(data.message);\n }\n else if (data.join) {\n this._handleJoin(channel, data.join);\n }\n else if (data.leave) {\n this._handleLeave(channel, data.leave);\n }\n else if (data.unsubscribe) {\n this._handleUnsubscribe(channel, data.unsubscribe);\n }\n else if (data.subscribe) {\n this._handleSubscribe(channel, data.subscribe);\n }\n else if (data.disconnect) {\n this._handleDisconnect(data.disconnect);\n }\n next();\n }\n _flush() {\n const commands = this._commands.slice(0);\n this._commands = [];\n this._transportSendCommands(commands);\n }\n _createErrorObject(code, message, temporary) {\n const errObject = {\n code: code,\n message: message\n };\n if (temporary) {\n errObject.temporary = true;\n }\n return errObject;\n }\n _registerCall(id, callback, errback) {\n this._callbacks[id] = {\n callback: callback,\n errback: errback,\n timeout: null\n };\n this._callbacks[id].timeout = setTimeout(() => {\n delete this._callbacks[id];\n if ((0, utils_1.isFunction)(errback)) {\n errback({ error: this._createErrorObject(codes_1.errorCodes.timeout, 'timeout') });\n }\n }, this._config.timeout);\n }\n _addCommand(command) {\n if (this._batching) {\n this._commands.push(command);\n }\n else {\n this._transportSendCommands([command]);\n }\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n}\nexports.Centrifuge = Centrifuge;\nCentrifuge.SubscriptionState = types_1.SubscriptionState;\nCentrifuge.State = types_1.State;\n//# sourceMappingURL=centrifuge.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.unsubscribedCodes = exports.subscribingCodes = exports.disconnectedCodes = exports.connectingCodes = exports.errorCodes = void 0;\nexports.errorCodes = {\n timeout: 1,\n transportClosed: 2,\n clientDisconnected: 3,\n clientClosed: 4,\n clientConnectToken: 5,\n clientRefreshToken: 6,\n subscriptionUnsubscribed: 7,\n subscriptionSubscribeToken: 8,\n subscriptionRefreshToken: 9,\n transportWriteError: 10,\n connectionClosed: 11\n};\nexports.connectingCodes = {\n connectCalled: 0,\n transportClosed: 1,\n noPing: 2,\n subscribeTimeout: 3,\n unsubscribeError: 4\n};\nexports.disconnectedCodes = {\n disconnectCalled: 0,\n unauthorized: 1,\n badProtocol: 2,\n messageSizeLimit: 3\n};\nexports.subscribingCodes = {\n subscribeCalled: 0,\n transportClosed: 1\n};\nexports.unsubscribedCodes = {\n unsubscribeCalled: 0,\n unauthorized: 1,\n clientClosed: 2\n};\n//# sourceMappingURL=codes.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Subscription = exports.Centrifuge = void 0;\nconst centrifuge_1 = require(\"./centrifuge\");\nObject.defineProperty(exports, \"Centrifuge\", { enumerable: true, get: function () { return centrifuge_1.Centrifuge; } });\nconst subscription_1 = require(\"./subscription\");\nObject.defineProperty(exports, \"Subscription\", { enumerable: true, get: function () { return subscription_1.Subscription; } });\n__exportStar(require(\"./types\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JsonDecoder = exports.JsonEncoder = void 0;\n/** @internal */\nclass JsonEncoder {\n encodeCommands(commands) {\n return commands.map(c => JSON.stringify(c)).join('\\n');\n }\n}\nexports.JsonEncoder = JsonEncoder;\n/** @internal */\nclass JsonDecoder {\n decodeReplies(data) {\n return data.trim().split('\\n').map(r => JSON.parse(r));\n }\n}\nexports.JsonDecoder = JsonDecoder;\n//# sourceMappingURL=json.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Subscription = void 0;\nconst events_1 = __importDefault(require(\"events\"));\nconst codes_1 = require(\"./codes\");\nconst types_1 = require(\"./types\");\nconst utils_1 = require(\"./utils\");\n/** Subscription to a channel */\nclass Subscription extends events_1.default {\n /** Subscription constructor should not be used directly, create subscriptions using Client method. */\n constructor(centrifuge, channel, options) {\n super();\n this._resubscribeTimeout = null;\n this._refreshTimeout = null;\n this.channel = channel;\n this.state = types_1.SubscriptionState.Unsubscribed;\n this._centrifuge = centrifuge;\n this._token = null;\n this._getToken = null;\n this._data = null;\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n this._recoverable = false;\n this._positioned = false;\n this._joinLeave = false;\n this._minResubscribeDelay = 500;\n this._maxResubscribeDelay = 20000;\n this._resubscribeTimeout = null;\n this._resubscribeAttempts = 0;\n this._promises = {};\n this._promiseId = 0;\n this._inflight = false;\n this._refreshTimeout = null;\n this._setOptions(options);\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n if (this._centrifuge._debugEnabled) {\n this.on('state', (ctx) => {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug('subscription state', channel, ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug('subscription error', channel, ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** ready returns a Promise which resolves upon subscription goes to Subscribed\n * state and rejects in case of subscription goes to Unsubscribed state.\n * Optional timeout can be passed.*/\n ready(timeout) {\n if (this.state === types_1.SubscriptionState.Unsubscribed) {\n return Promise.reject({ code: codes_1.errorCodes.subscriptionUnsubscribed, message: this.state });\n }\n if (this.state === types_1.SubscriptionState.Subscribed) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const ctx = {\n resolve: res,\n reject: rej\n };\n if (timeout) {\n ctx.timeout = setTimeout(function () {\n rej({ code: codes_1.errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[this._nextPromiseId()] = ctx;\n });\n }\n /** subscribe to a channel.*/\n subscribe() {\n if (this._isSubscribed()) {\n return;\n }\n this._resubscribeAttempts = 0;\n this._setSubscribing(codes_1.subscribingCodes.subscribeCalled, 'subscribe called');\n }\n /** unsubscribe from a channel, keeping position state.*/\n unsubscribe() {\n this._setUnsubscribed(codes_1.unsubscribedCodes.unsubscribeCalled, 'unsubscribe called', true);\n }\n /** publish data to a channel.*/\n publish(data) {\n const self = this;\n return this._methodCall().then(function () {\n return self._centrifuge.publish(self.channel, data);\n });\n }\n /** get online presence for a channel.*/\n presence() {\n const self = this;\n return this._methodCall().then(function () {\n return self._centrifuge.presence(self.channel);\n });\n }\n /** presence stats for a channel (num clients and unique users).*/\n presenceStats() {\n const self = this;\n return this._methodCall().then(function () {\n return self._centrifuge.presenceStats(self.channel);\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) – provide an explicit limit > 0 to load publications.*/\n history(opts) {\n const self = this;\n return this._methodCall().then(function () {\n return self._centrifuge.history(self.channel, opts);\n });\n }\n _methodCall() {\n if (this._isSubscribed()) {\n return Promise.resolve();\n }\n if (this._isUnsubscribed()) {\n return Promise.reject({ code: codes_1.errorCodes.subscriptionUnsubscribed, message: this.state });\n }\n return new Promise((res, rej) => {\n const timeout = setTimeout(function () {\n rej({ code: codes_1.errorCodes.timeout, message: 'timeout' });\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n }, this._centrifuge._config.timeout);\n this._promises[this._nextPromiseId()] = {\n timeout: timeout,\n resolve: res,\n reject: rej\n };\n });\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _needRecover() {\n return this._recover === true;\n }\n _isUnsubscribed() {\n return this.state === types_1.SubscriptionState.Unsubscribed;\n }\n _isSubscribing() {\n return this.state === types_1.SubscriptionState.Subscribing;\n }\n _isSubscribed() {\n return this.state === types_1.SubscriptionState.Subscribed;\n }\n _setState(newState) {\n if (this.state !== newState) {\n const oldState = this.state;\n this.state = newState;\n this.emit('state', { newState, oldState, channel: this.channel });\n return true;\n }\n return false;\n }\n _usesToken() {\n return this._token !== null || this._getToken !== null;\n }\n _clearSubscribingState() {\n this._resubscribeAttempts = 0;\n this._clearResubscribeTimeout();\n }\n _clearSubscribedState() {\n this._clearRefreshTimeout();\n }\n _setSubscribed(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._clearSubscribingState();\n if (result.recoverable) {\n this._recover = true;\n this._offset = result.offset || 0;\n this._epoch = result.epoch || '';\n }\n this._setState(types_1.SubscriptionState.Subscribed);\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getSubscribeContext(this.channel, result);\n this.emit('subscribed', ctx);\n this._resolvePromises();\n const pubs = result.publications;\n if (pubs && pubs.length > 0) {\n for (const i in pubs) {\n if (!pubs.hasOwnProperty(i)) {\n continue;\n }\n this._handlePublication(pubs[i]);\n }\n }\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), (0, utils_1.ttlMilliseconds)(result.ttl));\n }\n }\n _setSubscribing(code, reason) {\n if (this._isSubscribing()) {\n return;\n }\n if (this._isSubscribed()) {\n this._clearSubscribedState();\n }\n if (this._setState(types_1.SubscriptionState.Subscribing)) {\n this.emit('subscribing', { channel: this.channel, code: code, reason: reason });\n }\n this._subscribe(false, false);\n }\n _subscribe(optimistic, skipSending) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug('subscribing on', this.channel);\n if (this._centrifuge.state !== types_1.State.Connected && !optimistic) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug('delay subscribe on', this.channel, 'till connected');\n // subscribe will be called later automatically.\n return null;\n }\n if (this._usesToken()) {\n // token channel, need to get token before sending subscribe.\n if (this._token) {\n return this._sendSubscribe(this._token, skipSending);\n }\n else {\n if (optimistic) {\n return null;\n }\n const self = this;\n this._getSubscriptionToken().then(function (token) {\n if (!self._isSubscribing()) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._sendSubscribe(token, false);\n }).catch(function (e) {\n if (!self._isSubscribing()) {\n return;\n }\n self.emit('error', {\n type: 'subscribeToken',\n channel: self.channel,\n error: {\n code: codes_1.errorCodes.subscriptionSubscribeToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n self._scheduleResubscribe();\n });\n return null;\n }\n }\n else {\n return this._sendSubscribe('', skipSending);\n }\n }\n _sendSubscribe(token, skipSending) {\n const channel = this.channel;\n const req = {\n channel: channel\n };\n if (token) {\n req.token = token;\n }\n if (this._data) {\n req.data = this._data;\n }\n if (this._positioned) {\n req.positioned = true;\n }\n if (this._recoverable) {\n req.recoverable = true;\n }\n if (this._joinLeave) {\n req.join_leave = true;\n }\n if (this._needRecover()) {\n req.recover = true;\n const offset = this._getOffset();\n if (offset) {\n req.offset = offset;\n }\n const epoch = this._getEpoch();\n if (epoch) {\n req.epoch = epoch;\n }\n }\n const cmd = { subscribe: req };\n this._inflight = true;\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd, skipSending).then(resolveCtx => {\n this._inflight = false;\n // @ts-ignore - improve later.\n const result = resolveCtx.reply.subscribe;\n this._handleSubscribeResponse(result);\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n this._inflight = false;\n this._handleSubscribeError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n return cmd;\n }\n _handleSubscribeError(error) {\n if (!this._isSubscribing()) {\n return;\n }\n if (error.code === codes_1.errorCodes.timeout) {\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(codes_1.connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n return;\n }\n this._subscribeError(error);\n }\n _handleSubscribeResponse(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._setSubscribed(result);\n }\n _setUnsubscribed(code, reason, sendUnsubscribe) {\n if (this._isUnsubscribed()) {\n return;\n }\n if (this._isSubscribed()) {\n if (sendUnsubscribe) {\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n this._centrifuge._unsubscribe(this);\n }\n this._clearSubscribedState();\n }\n if (this._isSubscribing()) {\n this._clearSubscribingState();\n }\n if (this._setState(types_1.SubscriptionState.Unsubscribed)) {\n this.emit('unsubscribed', { channel: this.channel, code: code, reason: reason });\n }\n this._rejectPromises({ code: codes_1.errorCodes.subscriptionUnsubscribed, message: this.state });\n }\n _handlePublication(pub) {\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getPublicationContext(this.channel, pub);\n this.emit('publication', ctx);\n if (pub.offset) {\n this._offset = pub.offset;\n }\n }\n _handleJoin(join) {\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(join.info);\n this.emit('join', { channel: this.channel, info: info });\n }\n _handleLeave(leave) {\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(leave.info);\n this.emit('leave', { channel: this.channel, info: info });\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n _scheduleResubscribe() {\n const self = this;\n const delay = this._getResubscribeDelay();\n this._resubscribeTimeout = setTimeout(function () {\n if (self._isSubscribing()) {\n self._subscribe(false, false);\n }\n }, delay);\n }\n _subscribeError(err) {\n if (!this._isSubscribing()) {\n return;\n }\n if (err.code < 100 || err.code === 109 || err.temporary === true) {\n if (err.code === 109) { // Token expired error.\n this._token = null;\n }\n const errContext = {\n channel: this.channel,\n type: 'subscribe',\n error: err\n };\n if (this._centrifuge.state === types_1.State.Connected) {\n this.emit('error', errContext);\n }\n this._scheduleResubscribe();\n }\n else {\n this._setUnsubscribed(err.code, err.message, false);\n }\n }\n _getResubscribeDelay() {\n const delay = (0, utils_1.backoff)(this._resubscribeAttempts, this._minResubscribeDelay, this._maxResubscribeDelay);\n this._resubscribeAttempts++;\n return delay;\n }\n _setOptions(options) {\n if (!options) {\n return;\n }\n if (options.since) {\n this._offset = options.since.offset;\n this._epoch = options.since.epoch;\n this._recover = true;\n }\n if (options.data) {\n this._data = options.data;\n }\n if (options.minResubscribeDelay !== undefined) {\n this._minResubscribeDelay = options.minResubscribeDelay;\n }\n if (options.maxResubscribeDelay !== undefined) {\n this._maxResubscribeDelay = options.maxResubscribeDelay;\n }\n if (options.token) {\n this._token = options.token;\n }\n if (options.getToken) {\n this._getToken = options.getToken;\n }\n if (options.positioned === true) {\n this._positioned = true;\n }\n if (options.recoverable === true) {\n this._recoverable = true;\n }\n if (options.joinLeave === true) {\n this._joinLeave = true;\n }\n }\n _getOffset() {\n const offset = this._offset;\n if (offset !== null) {\n return offset;\n }\n return 0;\n }\n _getEpoch() {\n const epoch = this._epoch;\n if (epoch !== null) {\n return epoch;\n }\n return '';\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearResubscribeTimeout() {\n if (this._resubscribeTimeout !== null) {\n clearTimeout(this._resubscribeTimeout);\n this._resubscribeTimeout = null;\n }\n }\n _getSubscriptionToken() {\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n this._centrifuge._debug('get subscription token for channel', this.channel);\n const ctx = {\n channel: this.channel\n };\n const getToken = this._getToken;\n if (getToken === null) {\n throw new Error('provide a function to get channel subscription token');\n }\n return getToken(ctx);\n }\n _refresh() {\n this._clearRefreshTimeout();\n const self = this;\n this._getSubscriptionToken().then(function (token) {\n if (!self._isSubscribed()) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n const req = {\n channel: self.channel,\n token: token\n };\n const msg = {\n 'sub_refresh': req\n };\n // @ts-ignore – we are hiding some symbols from public API autocompletion.\n self._centrifuge._call(msg).then(resolveCtx => {\n // @ts-ignore - improve later.\n const result = resolveCtx.reply.sub_refresh;\n self._refreshResponse(result);\n // @ts-ignore - improve later.\n if (resolveCtx.next) {\n // @ts-ignore - improve later.\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._refreshError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }).catch(function (e) {\n self.emit('error', {\n type: 'refreshToken',\n channel: self.channel,\n error: {\n code: codes_1.errorCodes.subscriptionRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n }\n _refreshResponse(result) {\n if (!this._isSubscribed()) {\n return;\n }\n // @ts-ignore – we are hiding some methods from public API autocompletion.\n this._centrifuge._debug('subscription token refreshed, channel', this.channel);\n this._clearRefreshTimeout();\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), (0, utils_1.ttlMilliseconds)(result.ttl));\n }\n }\n _refreshError(err) {\n if (!this._isSubscribed()) {\n return;\n }\n if (err.code < 100 || err.temporary === true) {\n this.emit('error', {\n type: 'refresh',\n channel: this.channel,\n error: err\n });\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n }\n else {\n this._setUnsubscribed(err.code, err.message, true);\n }\n }\n _getRefreshRetryDelay() {\n return (0, utils_1.backoff)(0, 10000, 20000);\n }\n _failUnauthorized() {\n this._setUnsubscribed(codes_1.unsubscribedCodes.unauthorized, 'unauthorized', true);\n }\n}\nexports.Subscription = Subscription;\n//# sourceMappingURL=subscription.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpStreamTransport = void 0;\n/** @internal */\nclass HttpStreamTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._abortController = null;\n this._utf8decoder = new TextDecoder();\n this._protocol = 'json';\n }\n name() {\n return 'http_stream';\n }\n subName() {\n return 'http_stream';\n }\n emulation() {\n return true;\n }\n _handleErrors(response) {\n if (!response.ok)\n throw new Error(response.status);\n return response;\n }\n _fetchEventTarget(self, endpoint, options) {\n const eventTarget = new EventTarget();\n // fetch with connection timeout maybe? https://github.com/github/fetch/issues/175\n const fetchFunc = self.options.fetch;\n fetchFunc(endpoint, options)\n .then(self._handleErrors)\n .then(response => {\n eventTarget.dispatchEvent(new Event('open'));\n let jsonStreamBuf = '';\n let jsonStreamPos = 0;\n let protoStreamBuf = new Uint8Array();\n const reader = response.body.getReader();\n return new self.options.readableStream({\n start(controller) {\n function pump() {\n return reader.read().then(({ done, value }) => {\n // When no more data needs to be consumed, close the stream\n if (done) {\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n try {\n if (self._protocol === 'json') {\n jsonStreamBuf += self._utf8decoder.decode(value);\n while (jsonStreamPos < jsonStreamBuf.length) {\n if (jsonStreamBuf[jsonStreamPos] === '\\n') {\n const line = jsonStreamBuf.substring(0, jsonStreamPos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: line }));\n jsonStreamBuf = jsonStreamBuf.substring(jsonStreamPos + 1);\n jsonStreamPos = 0;\n }\n else {\n ++jsonStreamPos;\n }\n }\n }\n else {\n const mergedArray = new Uint8Array(protoStreamBuf.length + value.length);\n mergedArray.set(protoStreamBuf);\n mergedArray.set(value, protoStreamBuf.length);\n protoStreamBuf = mergedArray;\n while (true) {\n const result = self.options.decoder.decodeReply(protoStreamBuf);\n if (result.ok) {\n const data = protoStreamBuf.slice(0, result.pos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: data }));\n protoStreamBuf = protoStreamBuf.slice(result.pos);\n continue;\n }\n break;\n }\n }\n }\n catch (error) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n pump();\n }).catch(function (e) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: e }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n });\n }\n return pump();\n }\n });\n })\n .catch(error => {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n });\n return eventTarget;\n }\n supported() {\n return this.options.fetch !== null &&\n this.options.readableStream !== null &&\n typeof TextDecoder !== 'undefined' &&\n typeof AbortController !== 'undefined' &&\n typeof EventTarget !== 'undefined' &&\n typeof Event !== 'undefined' &&\n typeof MessageEvent !== 'undefined' &&\n typeof Error !== 'undefined';\n }\n initialize(protocol, callbacks, initialData) {\n this._protocol = protocol;\n this._abortController = new AbortController();\n let headers;\n let body;\n if (protocol === 'json') {\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n body = initialData;\n }\n else {\n headers = {\n 'Accept': 'application/octet-stream',\n 'Content-Type': 'application/octet-stream'\n };\n body = initialData;\n }\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n cache: 'no-cache',\n signal: this._abortController.signal\n };\n const eventTarget = this._fetchEventTarget(this, this.endpoint, fetchOptions);\n eventTarget.addEventListener('open', () => {\n callbacks.onOpen();\n });\n eventTarget.addEventListener('error', (e) => {\n this._abortController.abort();\n callbacks.onError(e);\n });\n eventTarget.addEventListener('close', () => {\n this._abortController.abort();\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n }\n close() {\n this._abortController.abort();\n }\n send(data, session, node) {\n let headers;\n let body;\n const req = {\n session: session,\n node: node,\n data: data\n };\n if (this._protocol === 'json') {\n headers = {\n 'Content-Type': 'application/json'\n };\n body = JSON.stringify(req);\n }\n else {\n headers = {\n 'Content-Type': 'application/octet-stream'\n };\n body = this.options.encoder.encodeEmulationRequest(req);\n }\n const fetchFunc = this.options.fetch;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n cache: 'no-cache'\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions);\n }\n}\nexports.HttpStreamTransport = HttpStreamTransport;\n//# sourceMappingURL=transport_http_stream.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SockjsTransport = void 0;\n/** @internal */\nclass SockjsTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'sockjs';\n }\n subName() {\n return 'sockjs-' + this._transport.transport;\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.sockjs !== null;\n }\n initialize(_protocol, callbacks) {\n this._transport = new this.options.sockjs(this.endpoint, null, this.options.sockjsOptions);\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n this._transport.close();\n }\n send(data) {\n this._transport.send(data);\n }\n}\nexports.SockjsTransport = SockjsTransport;\n//# sourceMappingURL=transport_sockjs.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SseTransport = void 0;\n/** @internal */\nclass SseTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._protocol = 'json';\n this._transport = null;\n this._onClose = null;\n }\n name() {\n return 'sse';\n }\n subName() {\n return 'sse';\n }\n emulation() {\n return true;\n }\n supported() {\n return this.options.eventsource !== null && this.options.fetch !== null;\n }\n initialize(_protocol, callbacks, initialData) {\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/sse\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n url.searchParams.append('cf_connect', initialData);\n const eventsourceOptions = {};\n const eventSource = new this.options.eventsource(url.toString(), eventsourceOptions);\n this._transport = eventSource;\n const self = this;\n eventSource.onopen = function () {\n callbacks.onOpen();\n };\n eventSource.onerror = function (e) {\n eventSource.close();\n callbacks.onError(e);\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n eventSource.onmessage = function (e) {\n callbacks.onMessage(e.data);\n };\n self._onClose = function () {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n }\n close() {\n this._transport.close();\n if (this._onClose !== null) {\n this._onClose();\n }\n }\n send(data, session, node) {\n const req = {\n session: session,\n node: node,\n data: data\n };\n const headers = {\n 'Content-Type': 'application/json'\n };\n const body = JSON.stringify(req);\n const fetchFunc = this.options.fetch;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n cache: 'no-cache'\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions);\n }\n}\nexports.SseTransport = SseTransport;\n//# sourceMappingURL=transport_sse.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WebsocketTransport = void 0;\n/** @internal */\nclass WebsocketTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'websocket';\n }\n subName() {\n return 'websocket';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.websocket !== undefined && this.options.websocket !== null;\n }\n initialize(protocol, callbacks) {\n let subProtocol = '';\n if (protocol === 'protobuf') {\n subProtocol = 'centrifuge-protobuf';\n }\n if (subProtocol !== '') {\n this._transport = new this.options.websocket(this.endpoint, subProtocol);\n }\n else {\n this._transport = new this.options.websocket(this.endpoint);\n }\n if (protocol === 'protobuf') {\n this._transport.binaryType = 'arraybuffer';\n }\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n this._transport.close();\n }\n send(data) {\n this._transport.send(data);\n }\n}\nexports.WebsocketTransport = WebsocketTransport;\n//# sourceMappingURL=transport_websocket.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\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) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WebtransportTransport = void 0;\n/** @internal */\nclass WebtransportTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n this._stream = null;\n this._writer = null;\n this._utf8decoder = new TextDecoder();\n this._protocol = 'json';\n }\n name() {\n return 'webtransport';\n }\n subName() {\n return 'webtransport';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.webtransport !== undefined && this.options.webtransport !== null;\n }\n initialize(protocol, callbacks) {\n return __awaiter(this, void 0, void 0, function* () {\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/webtransport\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n if (protocol === 'protobuf') {\n url.searchParams.append('cf_protocol', 'protobuf');\n }\n this._protocol = protocol;\n const eventTarget = new EventTarget();\n this._transport = new this.options.webtransport(url.toString());\n this._transport.closed.then(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n }).catch(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n try {\n yield this._transport.ready;\n }\n catch (_a) {\n this.close();\n return;\n }\n let stream;\n try {\n stream = yield this._transport.createBidirectionalStream();\n }\n catch (_b) {\n this.close();\n return;\n }\n this._stream = stream;\n this._writer = this._stream.writable.getWriter();\n eventTarget.addEventListener('close', () => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n this._startReading(eventTarget);\n callbacks.onOpen();\n });\n }\n _startReading(eventTarget) {\n return __awaiter(this, void 0, void 0, function* () {\n const reader = this._stream.readable.getReader();\n let jsonStreamBuf = '';\n let jsonStreamPos = 0;\n let protoStreamBuf = new Uint8Array();\n try {\n while (true) {\n const { done, value } = yield reader.read();\n if (value.length > 0) {\n if (this._protocol === 'json') {\n jsonStreamBuf += this._utf8decoder.decode(value);\n while (jsonStreamPos < jsonStreamBuf.length) {\n if (jsonStreamBuf[jsonStreamPos] === '\\n') {\n const line = jsonStreamBuf.substring(0, jsonStreamPos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: line }));\n jsonStreamBuf = jsonStreamBuf.substring(jsonStreamPos + 1);\n jsonStreamPos = 0;\n }\n else {\n ++jsonStreamPos;\n }\n }\n }\n else {\n const mergedArray = new Uint8Array(protoStreamBuf.length + value.length);\n mergedArray.set(protoStreamBuf);\n mergedArray.set(value, protoStreamBuf.length);\n protoStreamBuf = mergedArray;\n while (true) {\n const result = this.options.decoder.decodeReply(protoStreamBuf);\n if (result.ok) {\n const data = protoStreamBuf.slice(0, result.pos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: data }));\n protoStreamBuf = protoStreamBuf.slice(result.pos);\n continue;\n }\n break;\n }\n }\n }\n if (done) {\n break;\n }\n }\n }\n catch (_a) {\n eventTarget.dispatchEvent(new Event('close'));\n }\n });\n }\n close() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n if (this._writer) {\n yield this._writer.close();\n }\n this._transport.close();\n }\n catch (e) {\n // already closed.\n }\n });\n }\n send(data) {\n return __awaiter(this, void 0, void 0, function* () {\n let binary;\n if (this._protocol === 'json') {\n // Need extra \\n since WT is non-frame protocol. \n binary = new TextEncoder().encode(data + '\\n');\n }\n else {\n binary = data;\n }\n try {\n yield this._writer.write(binary);\n }\n catch (e) {\n this.close();\n }\n });\n }\n}\nexports.WebtransportTransport = WebtransportTransport;\n//# sourceMappingURL=transport_webtransport.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SubscriptionState = exports.State = void 0;\n/** State of client. */\nvar State;\n(function (State) {\n State[\"Disconnected\"] = \"disconnected\";\n State[\"Connecting\"] = \"connecting\";\n State[\"Connected\"] = \"connected\";\n})(State = exports.State || (exports.State = {}));\n/** State of Subscription */\nvar SubscriptionState;\n(function (SubscriptionState) {\n SubscriptionState[\"Unsubscribed\"] = \"unsubscribed\";\n SubscriptionState[\"Subscribing\"] = \"subscribing\";\n SubscriptionState[\"Subscribed\"] = \"subscribed\";\n})(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ttlMilliseconds = exports.errorExists = exports.backoff = exports.log = exports.isFunction = exports.startsWith = void 0;\n/** @internal */\nfunction startsWith(value, prefix) {\n return value.lastIndexOf(prefix, 0) === 0;\n}\nexports.startsWith = startsWith;\n/** @internal */\nfunction isFunction(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'function';\n}\nexports.isFunction = isFunction;\n/** @internal */\nfunction log(level, args) {\n if (globalThis.console) {\n const logger = globalThis.console[level];\n if (isFunction(logger)) {\n logger.apply(globalThis.console, args);\n }\n }\n}\nexports.log = log;\nfunction randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/** @internal */\nfunction backoff(step, min, max) {\n // Full jitter technique, see:\n // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n if (step > 31) {\n step = 31;\n }\n const interval = randomInt(0, Math.min(max, min * Math.pow(2, step)));\n return Math.min(max, min + interval);\n}\nexports.backoff = backoff;\n/** @internal */\nfunction errorExists(data) {\n return 'error' in data && data.error !== null;\n}\nexports.errorExists = errorExists;\n/** @internal */\nfunction ttlMilliseconds(ttl) {\n // https://stackoverflow.com/questions/12633405/what-is-the-maximum-delay-for-setinterval\n return Math.min(ttl * 1000, 2147483647);\n}\nexports.ttlMilliseconds = ttlMilliseconds;\n//# sourceMappingURL=utils.js.map","// 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;\nmodule.exports.once = once;\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\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\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 checkListener(listener);\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 if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\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 checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\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 checkListener(listener);\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\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n return createProxy(ep, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n ep.addEventListener(\"message\", function l(ev) {\n if (!ev.data || !ev.data.id || ev.data.id !== id) {\n return;\n }\n ep.removeEventListener(\"message\", l);\n resolve(ev.data);\n });\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n"],"names":["bufferIfNot","canEmitObservable","source","Observable","subscriber","buffer","canEmit","emitBuffer","canEmitSub","val","sourceSub","value","error","InternalStreamMessageType","reduceNewValuesSameSchemaMessages","packets","acc","values","i","j","filterMessages","type","p","LiveDataStream","deps","ReplaySubject","err","toDataQueryError","evt","liveChannelStatusEvent","msg","bufferOptions","options","subKey","shouldSendLastPacketOnly","fieldsNamesFilter","fieldFilterPredicate","name","matchingFieldIndexes","getFullFrameResponseData","messages","getNewValuesSameSchemaResponseData","lastMessage","filteredValues","v","shouldSendFullFrame","transformedInternalStream","map","errors","lastError","n","newValueSameSchemaMessages","sub","StreamingDataFrame","CentrifugeLiveChannel","id","addr","Subject","ctx","message","copy","initialMessage","getErrorChannel","defaultStreamingFrameOptions","dataStreamShutdownDelayInMs","CentrifugeService","context","address","streamCounter","channelId","existingStream","channel","subscriptionKey","share","startWith","liveUrl","token","BehaviorSubject","resolve","connectListener","subscription","subscriberTransferHandler","obj","port1","port2","__importDefault","mod","exports","subscription_1","codes_1","transport_sockjs_1","transport_websocket_1","transport_http_stream_1","transport_sse_1","transport_webtransport_1","json_1","utils_1","types_1","events_1","defaults","Centrifuge","endpoint","timeout","res","rej","data","cmd","self","method","reply","result","publications","args","format","_format","transportConfig","transportName","newState","oldState","eventTarget","delay","callbacks","errback","commands","command","e","websocket","sockjs","eventsource","fetchFunc","readableStream","count","transportEndpoint","wasOpen","optimistic","initialCommands","connectCommand","subscribeCommands","initialData","closeEvent","reason","needReconnect","code","advice","isInitialHandshake","skipSending","resolveCtx","rejectCtx","req","subs","hasSubs","resultCB","reject","replies","finishDispatch","next","reconnect","previousState","needEvent","clientId","subCtx","pubs","epoch","offset","callback","join","leave","unsubscribe","disconnect","pub","clientInfo","info","temporary","errObject","__createBinding","o","m","k","k2","desc","__exportStar","centrifuge_1","JsonEncoder","c","JsonDecoder","r","Subscription","centrifuge","opts","sendUnsubscribe","errContext","getToken","HttpStreamTransport","response","jsonStreamBuf","jsonStreamPos","protoStreamBuf","reader","controller","pump","done","line","mergedArray","protocol","headers","body","fetchOptions","session","node","SockjsTransport","_protocol","event","SseTransport","url","eventsourceOptions","eventSource","WebsocketTransport","subProtocol","__awaiter","thisArg","_arguments","P","generator","adopt","fulfilled","step","rejected","WebtransportTransport","stream","binary","State","SubscriptionState","startsWith","prefix","isFunction","log","level","logger","randomInt","min","max","backoff","interval","errorExists","ttlMilliseconds","ttl","R","ReflectApply","target","receiver","ReflectOwnKeys","ProcessEmitWarning","warning","NumberIsNaN","EventEmitter","module","once","defaultMaxListeners","checkListener","listener","arg","_getMaxListeners","that","doError","events","er","handler","len","listeners","arrayClone","_addListener","prepend","existing","w","onceWrapper","_onceWrap","state","wrapped","list","position","originalListener","spliceOne","keys","key","_listeners","unwrap","evlistener","unwrapListeners","emitter","listenerCount","arr","index","ret","errorListener","resolver","eventTargetAgnosticAddListener","addErrorHandlerIfEventEmitter","flags","wrapListener","proxyMarker","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","proxyTransferHandler","expose","port","wrap","throwTransferHandler","serialized","transferHandlers","isAllowedOrigin","allowedOrigins","origin","allowedOrigin","ep","ev","path","argumentList","fromWireValue","returnValue","parent","prop","rawValue","proxy","transfer","wireValue","transferables","toWireValue","closeEndPoint","isMessagePort","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","proxyFinalizers","newCount","registerProxy","unregisterProxy","isProxyReleased","_target","_thisArg","rawArgumentList","last","processArguments","myFlat","processed","transferCache","transfers","windowEndpoint","targetOrigin","serializedValue","generateUUID","l"],"sourceRoot":""}