react-websocket 4.22.1 → 4.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ag-ui.cjs +7 -7
- package/dist/ag-ui.cjs.map +1 -1
- package/dist/ag-ui.d.cts +3 -2
- package/dist/ag-ui.js +7 -7
- package/dist/ag-ui.js.map +1 -1
- package/dist/chaos.cjs +59 -11
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts +1 -0
- package/dist/chaos.d.ts +1 -0
- package/dist/chaos.js +59 -11
- package/dist/chaos.js.map +1 -1
- package/dist/core.cjs +82 -43
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +4 -3
- package/dist/core.d.ts +4 -3
- package/dist/core.js +82 -43
- package/dist/core.js.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +3 -2
- package/dist/outbox.cjs +14 -8
- package/dist/outbox.cjs.map +1 -1
- package/dist/outbox.d.cts +1 -1
- package/dist/outbox.js +14 -8
- package/dist/outbox.js.map +1 -1
- package/dist/replay.cjs +12 -7
- package/dist/replay.cjs.map +1 -1
- package/dist/replay.d.cts +8 -2
- package/dist/replay.d.ts +8 -2
- package/dist/replay.js +12 -7
- package/dist/replay.js.map +1 -1
- package/dist/tabs.cjs +11 -14
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs.js +11 -14
- package/dist/tabs.js.map +1 -1
- package/dist/timeline.cjs +3 -1
- package/dist/timeline.cjs.map +1 -1
- package/dist/timeline.d.cts +3 -3
- package/dist/timeline.d.ts +2 -2
- package/dist/timeline.js +3 -1
- package/dist/timeline.js.map +1 -1
- package/dist/{types-paLT8yQF.d.cts → types-Bb3sBG8L.d.cts} +4 -3
- package/dist/webtransport.cjs +12 -10
- package/dist/webtransport.cjs.map +1 -1
- package/dist/webtransport.js +12 -10
- package/dist/webtransport.js.map +1 -1
- package/package.json +6 -6
package/dist/replay.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replay.js","names":[],"sources":["../src/replay.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Data in a recording: text as it was, binary as base64. */\nexport type RecordedData = string | { readonly binary: string };\n\n/** One event of a recorded connection, `t` ms after it was created. */\nexport type RecordedEvent =\n | { readonly t: number; readonly type: 'open'; readonly protocol: string }\n | { readonly t: number; readonly type: 'send' | 'message'; readonly data: RecordedData }\n | { readonly t: number; readonly type: 'error' }\n | {\n readonly t: number;\n readonly type: 'close';\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n };\n\n/** A recorded event before its time is known. */\ntype Untimed = RecordedEvent extends infer E\n ? E extends RecordedEvent\n ? Omit<E, 't'>\n : never\n : never;\n\n/** A recorded session: every connection, in the order they were opened. Plain JSON. */\nexport interface WebSocketRecording {\n readonly format: 'react-websocket-recording';\n readonly version: 1;\n readonly connections: readonly {\n readonly url: string;\n /** When it was created, from `Date.now()`. */\n readonly at: number;\n readonly events: readonly RecordedEvent[];\n }[];\n}\n\n/** The class from {@link createRecordingWebSocket}: a `WebSocket` that records what it does. */\nexport interface RecordingWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** Everything recorded so far, as a new plain object. */\n recording(): WebSocketRecording;\n /** Download the recording as a JSON file, e.g. from a \"Report a problem\" button. */\n save(filename?: string): void;\n /** Forget everything recorded so far. */\n clear(): void;\n}\n\n/** Options for {@link createReplayWebSocket}. */\nexport interface ReplayOptions {\n /**\n * How fast to replay: `1` is the recorded timing, `4` four times faster, `Infinity` as fast as\n * possible, each event in a task of its own.\n * @default 1\n */\n speed?: number;\n /**\n * Wait for the app to send before replaying what came after a send in the recording, so the\n * replay follows the app instead of the clock: a server's answer comes after the question,\n * however long the app takes to ask. `false` follows the recorded timing alone.\n * @default true\n */\n waitForSends?: boolean;\n}\n\n/** The class from {@link createReplayWebSocket}: a `WebSocket` that plays a recording back. */\nexport interface ReplayWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** What the app sent during the replay, by connection, as recorded data. */\n readonly sent: readonly RecordedData[][];\n /** Resolves once every recorded connection has been played to its end. */\n readonly done: Promise<void>;\n /** Start again from the first recorded connection. */\n reset(): void;\n}\n\ninterface Statics {\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nfunction encode(bytes: ArrayBuffer | ArrayBufferView): RecordedData {\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let text = '';\n for (const byte of view) text += String.fromCharCode(byte);\n return { binary: btoa(text) };\n}\n\nfunction decode(data: RecordedData, binaryType: BinaryType): unknown {\n if (typeof data === 'string') return data;\n const buffer = Uint8Array.from(atob(data.binary), char => char.charCodeAt(0)).buffer;\n return binaryType === 'blob' ? new Blob([buffer]) : buffer;\n}\n\n/** Shared by both classes: the `WebSocket` surface over a state and some events. */\nclass Base extends EventTarget {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n protocol = '';\n state: WebSocket['readyState'] = CONNECTING;\n\n constructor(url: string | URL) {\n super();\n this.url = String(url);\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n }\n\n get readyState() {\n return this.state;\n }\n\n opened(protocol: string) {\n this.state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n received(data: unknown) {\n if (this.state === OPEN) this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n ended(code: number, reason: string, wasClean: boolean) {\n if (this.state === CLOSED) return;\n this.state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n}\n\n/**\n * A `WebSocket` class that records what its connections do: when each one opened, every message\n * sent and received, errors and closes. Pass it as the `WebSocket` option, and get the session\n * back with `recording()`, or download it with `save()`, to attach to a bug report or replay\n * with {@link createReplayWebSocket}.\n *\n * Recordings hold every message, so they can hold tokens and personal data: record in\n * development, or ask before saving one from a user's session.\n *\n * @example\n * ```ts\n * import { createRecordingWebSocket } from 'react-websocket/replay';\n *\n * export const Recorder = createRecordingWebSocket();\n * export const live = createWebSocket(url, { WebSocket: Recorder });\n *\n * reportButton.onclick = () => Recorder.save('session.json');\n * ```\n */\nexport function createRecordingWebSocket(\n options: { WebSocket?: typeof WebSocket } = {}\n): RecordingWebSocket {\n let connections: { url: string; at: number; events: RecordedEvent[] }[] = [];\n\n class RecordingSocket extends Base implements WebSocket {\n #inner: WebSocket;\n #binaryType: BinaryType = 'blob';\n\n static recording(): WebSocketRecording {\n return JSON.parse(\n JSON.stringify({ format: 'react-websocket-recording', version: 1, connections })\n );\n }\n\n static save(filename = 'websocket-recording.json') {\n const url = URL.createObjectURL(\n new Blob([JSON.stringify(RecordingSocket.recording(), null, 2)], {\n type: 'application/json'\n })\n );\n const link = Object.assign(document.createElement('a'), { href: url, download: filename });\n link.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n\n static clear() {\n connections = [];\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n const inner = (this.#inner = new Impl(url, protocols));\n // Binary data arrives as an ArrayBuffer, to record it without waiting on a Blob.\n inner.binaryType = 'arraybuffer';\n const start = performance.now();\n const events: RecordedEvent[] = [];\n connections.push({ url: this.url, at: Date.now(), events });\n const record = (event: Untimed) =>\n events.push({ t: Math.round(performance.now() - start), ...event } as RecordedEvent);\n this.#record = record;\n inner.onopen = () => {\n record({ type: 'open', protocol: inner.protocol ?? '' });\n this.opened(inner.protocol);\n };\n inner.onmessage = event => {\n const data = event.data as string | ArrayBuffer;\n record({ type: 'message', data: typeof data === 'string' ? data : encode(data) });\n this.received(\n typeof data === 'string' || this.#binaryType !== 'blob' ? data : new Blob([data])\n );\n };\n inner.onerror = () => {\n record({ type: 'error' });\n this.dispatchEvent(new Event('error'));\n };\n inner.onclose = event => {\n record({ type: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n this.ended(event.code, event.reason, event.wasClean);\n };\n }\n\n #record: (event: Untimed) => void;\n\n get binaryType() {\n return this.#binaryType;\n }\n\n set binaryType(value) {\n this.#binaryType = value;\n }\n\n get bufferedAmount() {\n return this.#inner.bufferedAmount;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n this.#inner.send(data);\n if (typeof data === 'string') this.#record({ type: 'send', data });\n else if (data instanceof Blob) {\n // Recorded where it was sent; its bytes are filled in once read.\n const event = { type: 'send', data: { binary: '' } } as const;\n this.#record(event);\n void data.arrayBuffer().then(buffer => Object.assign(event.data, encode(buffer)));\n } else this.#record({ type: 'send', data: encode(data) });\n }\n\n close(code?: number, reason?: string) {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#inner.close(code, reason);\n }\n }\n\n return RecordingSocket as unknown as RecordingWebSocket;\n}\n\n/**\n * A `WebSocket` class that plays a recording back, without a server: each connection the client\n * opens replays the next recorded one, with its open, messages, errors and close, at the recorded\n * timing or faster. For reproducing a bug report, offline demos, and UI tests that don't call a\n * live backend, such as an AI model, on every run.\n *\n * By default, what came after a send in the recording waits until the app sends too, so the\n * replay follows the app. Wrap it with `createChaosWebSocket({ WebSocket: Replay })` to add\n * faults.\n *\n * @example\n * ```ts\n * import { createReplayWebSocket } from 'react-websocket/replay';\n * import recording from './fixtures/chat.json';\n *\n * const Replay = createReplayWebSocket(recording, { speed: Infinity });\n * render(<Chat client={createWebSocket(url, { WebSocket: Replay })} />);\n * await Replay.done;\n * ```\n */\nexport function createReplayWebSocket(\n recording: WebSocketRecording,\n options: ReplayOptions = {}\n): ReplayWebSocket {\n const speed = options.speed ?? 1;\n const waitForSends = options.waitForSends ?? true;\n let next = 0;\n let sent: RecordedData[][] = [];\n let finish: () => void;\n let done = new Promise<void>(resolve => (finish = resolve));\n const live = new Set<ReplaySocket>();\n\n class ReplaySocket extends Base implements WebSocket {\n binaryType: BinaryType = 'blob';\n readonly bufferedAmount = 0;\n #events: readonly RecordedEvent[];\n #index = 0;\n #sent: RecordedData[] = [];\n // The recorded time the timeline is at, and the real time it was there.\n #recordedAt = 0;\n #realAt = performance.now();\n #timer: ReturnType<typeof setTimeout> | undefined;\n // Recorded sends passed so far, and whether the timeline waits for the app to send.\n #sends = 0;\n #paused = false;\n\n static get sent() {\n return sent;\n }\n\n static get done() {\n return done;\n }\n\n static reset() {\n for (const socket of live) socket.#stop();\n next = 0;\n sent = [];\n done = new Promise<void>(resolve => (finish = resolve));\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n void protocols;\n const connection = recording.connections[next++];\n sent.push(this.#sent);\n // More connections than were recorded: refused, like a server that's gone.\n this.#events = connection?.events ?? [\n { t: 0, type: 'error' },\n { t: 0, type: 'close', code: 1006, reason: '', wasClean: false }\n ];\n live.add(this);\n this.#schedule();\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.state !== OPEN) return;\n this.#sent.push(\n typeof data === 'string' ? data : data instanceof Blob ? { binary: '' } : encode(data)\n );\n if (this.#paused) {\n this.#paused = false;\n this.#schedule();\n }\n }\n\n close(code = 1000, reason = '') {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#stop();\n setTimeout(() => this.ended(code, reason, true), 0);\n }\n\n #schedule(): void {\n clearTimeout(this.#timer);\n const event = this.#events[this.#index];\n if (!event || this.state === CLOSED) return this.#finished();\n if (event.type === 'send') {\n if (waitForSends) {\n // Wait until the app has sent as many messages, then go on from that moment.\n if (this.#sent.length <= this.#sends) return void (this.#paused = true);\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n }\n this.#index++;\n this.#sends++;\n return this.#schedule();\n }\n const wait = (event.t - this.#recordedAt) / speed - (performance.now() - this.#realAt);\n this.#timer = setTimeout(\n () => this.#play(event),\n Math.max(0, Number.isFinite(wait) ? wait : 0)\n );\n }\n\n #play(event: RecordedEvent) {\n this.#index++;\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n if (event.type === 'open') this.opened(event.protocol);\n else if (event.type === 'message') this.received(decode(event.data, this.binaryType));\n else if (event.type === 'error') this.dispatchEvent(new Event('error'));\n else if (event.type === 'close') {\n this.#stop();\n return this.ended(event.code, event.reason, event.wasClean);\n }\n this.#schedule();\n }\n\n #stop() {\n clearTimeout(this.#timer);\n this.#index = this.#events.length;\n this.#finished();\n }\n\n #finished() {\n live.delete(this);\n if (next >= recording.connections.length && !live.size) finish();\n }\n }\n\n return ReplaySocket as unknown as ReplayWebSocket;\n}\n"],"mappings":";AAqFA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAEf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,SAAS,OAAO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AAK,UAAU;EACjB;EAEA,YAAY;GACV,KAAK,OAAO,IAAI;GAChB,IAAI,QAAQ,UAAU,YAAY,UAAU,CAAC,KAAK,MAAM,OAAO;EACjE;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"replay.js","names":[],"sources":["../src/replay.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Data in a recording: text as it was, binary as base64. */\nexport type RecordedData = string | { readonly binary: string };\n\n/** One event of a recorded connection, `t` ms after it was created. */\nexport type RecordedEvent =\n | { readonly t: number; readonly type: 'open'; readonly protocol: string }\n | { readonly t: number; readonly type: 'send' | 'message'; readonly data: RecordedData }\n | { readonly t: number; readonly type: 'error' }\n | {\n readonly t: number;\n readonly type: 'close';\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n };\n\n/** A recorded event before its time is known. */\ntype Untimed = RecordedEvent extends infer E\n ? E extends RecordedEvent\n ? Omit<E, 't'>\n : never\n : never;\n\n/** A recorded session: every connection, in the order they were opened. Plain JSON. */\nexport interface WebSocketRecording {\n readonly format: 'react-websocket-recording';\n readonly version: 1;\n readonly connections: readonly {\n readonly url: string;\n /** When it was created, from `Date.now()`. */\n readonly at: number;\n readonly events: readonly RecordedEvent[];\n }[];\n}\n\n/** The class from {@link createRecordingWebSocket}: a `WebSocket` that records what it does. */\nexport interface RecordingWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** Everything recorded so far, as a new plain object. */\n recording(): WebSocketRecording;\n /** Download the recording as a JSON file, e.g. from a \"Report a problem\" button. */\n save(filename?: string): void;\n /** Forget everything recorded so far. */\n clear(): void;\n}\n\n/** Options for {@link createReplayWebSocket}. */\nexport interface ReplayOptions {\n /**\n * How fast to replay: `1` is the recorded timing, `4` four times faster, `Infinity` as fast as\n * possible, each event in a task of its own.\n * @default 1\n */\n speed?: number;\n /**\n * Wait for the app to send before replaying what came after a send in the recording, so the\n * replay follows the app instead of the clock: a server's answer comes after the question,\n * however long the app takes to ask. `false` follows the recorded timing alone.\n * @default true\n */\n waitForSends?: boolean;\n}\n\n/** The class from {@link createReplayWebSocket}: a `WebSocket` that plays a recording back. */\nexport interface ReplayWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** What the app sent during the replay, by connection, as recorded data. */\n readonly sent: readonly RecordedData[][];\n /**\n * Resolves once every recorded connection has been played to its end, after its last `close`\n * event.\n */\n readonly done: Promise<void>;\n /**\n * Start again from the first recorded connection. Connections still playing stop where they are,\n * without a `close` event.\n */\n reset(): void;\n}\n\ninterface Statics {\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nfunction encode(bytes: ArrayBuffer | ArrayBufferView): RecordedData {\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let text = '';\n for (const byte of view) text += String.fromCharCode(byte);\n return { binary: btoa(text) };\n}\n\nfunction decode(data: RecordedData, binaryType: BinaryType): unknown {\n if (typeof data === 'string') return data;\n const buffer = Uint8Array.from(atob(data.binary), char => char.charCodeAt(0)).buffer;\n return binaryType === 'blob' ? new Blob([buffer]) : buffer;\n}\n\n/** Shared by both classes: the `WebSocket` surface over a state and some events. */\nclass Base extends EventTarget {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n protocol = '';\n state: WebSocket['readyState'] = CONNECTING;\n\n constructor(url: string | URL) {\n super();\n this.url = String(url);\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n }\n\n get readyState() {\n return this.state;\n }\n\n opened(protocol: string) {\n this.state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n received(data: unknown) {\n if (this.state === OPEN) this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n ended(code: number, reason: string, wasClean: boolean) {\n if (this.state === CLOSED) return;\n this.state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n}\n\n/**\n * A `WebSocket` class that records what its connections do: when each one opened, every message\n * sent and received, errors and closes. Pass it as the `WebSocket` option, and get the session\n * back with `recording()`, or download it with `save()`, to attach to a bug report or replay\n * with {@link createReplayWebSocket}.\n *\n * Recordings hold every message, so they can hold tokens and personal data: record in\n * development, or ask before saving one from a user's session.\n *\n * @example\n * ```ts\n * import { createRecordingWebSocket } from 'react-websocket/replay';\n *\n * export const Recorder = createRecordingWebSocket();\n * export const live = createWebSocket(url, { WebSocket: Recorder });\n *\n * reportButton.onclick = () => Recorder.save('session.json');\n * ```\n */\nexport function createRecordingWebSocket(\n options: { WebSocket?: typeof WebSocket } = {}\n): RecordingWebSocket {\n let connections: { url: string; at: number; events: RecordedEvent[] }[] = [];\n\n class RecordingSocket extends Base implements WebSocket {\n #inner: WebSocket;\n #binaryType: BinaryType = 'blob';\n\n static recording(): WebSocketRecording {\n return JSON.parse(\n JSON.stringify({ format: 'react-websocket-recording', version: 1, connections })\n );\n }\n\n static save(filename = 'websocket-recording.json') {\n const url = URL.createObjectURL(\n new Blob([JSON.stringify(RecordingSocket.recording(), null, 2)], {\n type: 'application/json'\n })\n );\n const link = Object.assign(document.createElement('a'), { href: url, download: filename });\n link.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n\n static clear() {\n connections = [];\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n const inner = (this.#inner = new Impl(url, protocols));\n // Binary data arrives as an ArrayBuffer, to record it without waiting on a Blob.\n inner.binaryType = 'arraybuffer';\n const start = performance.now();\n const events: RecordedEvent[] = [];\n connections.push({ url: this.url, at: Date.now(), events });\n const record = (event: Untimed) =>\n events.push({ t: Math.round(performance.now() - start), ...event } as RecordedEvent);\n this.#record = record;\n inner.onopen = () => {\n record({ type: 'open', protocol: inner.protocol ?? '' });\n this.opened(inner.protocol);\n };\n inner.onmessage = event => {\n const data = event.data as string | ArrayBuffer;\n record({ type: 'message', data: typeof data === 'string' ? data : encode(data) });\n this.received(\n typeof data === 'string' || this.#binaryType !== 'blob' ? data : new Blob([data])\n );\n };\n inner.onerror = () => {\n record({ type: 'error' });\n this.dispatchEvent(new Event('error'));\n };\n inner.onclose = event => {\n record({ type: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n this.ended(event.code, event.reason, event.wasClean);\n };\n }\n\n #record: (event: Untimed) => void;\n\n get binaryType() {\n return this.#binaryType;\n }\n\n set binaryType(value) {\n this.#binaryType = value;\n }\n\n get bufferedAmount() {\n return this.#inner.bufferedAmount;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n this.#inner.send(data);\n if (typeof data === 'string') this.#record({ type: 'send', data });\n else if (data instanceof Blob) {\n // Recorded where it was sent; its bytes are filled in once read.\n const event = { type: 'send', data: { binary: '' } } as const;\n this.#record(event);\n void data.arrayBuffer().then(buffer => Object.assign(event.data, encode(buffer)));\n } else this.#record({ type: 'send', data: encode(data) });\n }\n\n close(code?: number, reason?: string) {\n if (this.state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n this.#inner.close(code, reason);\n this.state = CLOSING;\n }\n }\n\n return RecordingSocket as unknown as RecordingWebSocket;\n}\n\n/**\n * A `WebSocket` class that plays a recording back, without a server: each connection the client\n * opens replays the next recorded one, with its open, messages, errors and close, at the recorded\n * timing or faster. For reproducing a bug report, offline demos, and UI tests that don't call a\n * live backend, such as an AI model, on every run.\n *\n * By default, what came after a send in the recording waits until the app sends too, so the\n * replay follows the app. Wrap it with `createChaosWebSocket({ WebSocket: Replay })` to add\n * faults.\n *\n * @example\n * ```ts\n * import { createReplayWebSocket } from 'react-websocket/replay';\n * import recording from './fixtures/chat.json';\n *\n * const Replay = createReplayWebSocket(recording, { speed: Infinity });\n * render(<Chat client={createWebSocket(url, { WebSocket: Replay })} />);\n * await Replay.done;\n * ```\n */\nexport function createReplayWebSocket(\n recording: WebSocketRecording,\n options: ReplayOptions = {}\n): ReplayWebSocket {\n const speed = options.speed ?? 1;\n const waitForSends = options.waitForSends ?? true;\n let next = 0;\n let sent: RecordedData[][] = [];\n let finish: () => void;\n let done = new Promise<void>(resolve => (finish = resolve));\n const live = new Set<ReplaySocket>();\n\n class ReplaySocket extends Base implements WebSocket {\n binaryType: BinaryType = 'blob';\n readonly bufferedAmount = 0;\n #events: readonly RecordedEvent[];\n #index = 0;\n #sent: RecordedData[] = [];\n // The recorded time the timeline is at, and the real time it was there.\n #recordedAt = 0;\n #realAt = performance.now();\n #timer: ReturnType<typeof setTimeout> | undefined;\n // Recorded sends passed so far, and whether the timeline waits for the app to send.\n #sends = 0;\n #paused = false;\n\n static get sent() {\n return sent;\n }\n\n static get done() {\n return done;\n }\n\n static reset() {\n for (const socket of live) {\n socket.#stop();\n socket.#finished();\n }\n next = 0;\n sent = [];\n done = new Promise<void>(resolve => (finish = resolve));\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n void protocols;\n const connection = recording.connections[next++];\n sent.push(this.#sent);\n // More connections than were recorded: refused, like a server that's gone.\n this.#events = connection?.events ?? [\n { t: 0, type: 'error' },\n { t: 0, type: 'close', code: 1006, reason: '', wasClean: false }\n ];\n live.add(this);\n this.#schedule();\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.state !== OPEN) return;\n this.#sent.push(\n typeof data === 'string' ? data : data instanceof Blob ? { binary: '' } : encode(data)\n );\n if (this.#paused) {\n this.#paused = false;\n this.#schedule();\n }\n }\n\n close(code = 1000, reason = '') {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#stop();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #schedule(): void {\n clearTimeout(this.#timer);\n const event = this.#events[this.#index];\n if (!event || this.state === CLOSED) return this.#finished();\n if (event.type === 'send') {\n if (waitForSends) {\n // Wait until the app has sent as many messages, then go on from that moment.\n if (this.#sent.length <= this.#sends) return void (this.#paused = true);\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n }\n this.#index++;\n this.#sends++;\n return this.#schedule();\n }\n const wait = (event.t - this.#recordedAt) / speed - (performance.now() - this.#realAt);\n this.#timer = setTimeout(\n () => this.#play(event),\n Math.max(0, Number.isFinite(wait) ? wait : 0)\n );\n }\n\n #play(event: RecordedEvent) {\n this.#index++;\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n if (event.type === 'open') this.opened(event.protocol);\n else if (event.type === 'message') this.received(decode(event.data, this.binaryType));\n else if (event.type === 'error') this.dispatchEvent(new Event('error'));\n else if (event.type === 'close') return this.#end(event.code, event.reason, event.wasClean);\n this.#schedule();\n }\n\n #stop() {\n clearTimeout(this.#timer);\n this.#index = this.#events.length;\n }\n\n /** Finished once the close event is out, so `done` comes after it. */\n #end(code: number, reason: string, wasClean: boolean) {\n this.#stop();\n this.ended(code, reason, wasClean);\n this.#finished();\n }\n\n #finished() {\n live.delete(this);\n if (next >= recording.connections.length && !live.size) finish();\n }\n }\n\n return Re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I,MAAM,SAAS,WAAW,KAAK,SAAS,OAAO,MAAM,MAAM,KAAK,UAAU,CAAC;QAC/E,IAAI,MAAM,SAAS,SAAS,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;QACjE,IAAI,MAAM,SAAS,SAAS,OAAO,KAAK,KAAK,MAAM,MAAM,MAAM,QAAQ,MAAM,QAAQ;GAC1F,KAAK,UAAU;EACjB;EAEA,QAAQ;GACN,aAAa,KAAK,MAAM;GACxB,KAAK,SAAS,KAAK,QAAQ;EAC7B;;EAGA,KAAK,MAAc,QAAgB,UAAmB;GACpD,KAAK,MAAM;GACX,KAAK,MAAM,MAAM,QAAQ,QAAQ;GACjC,KAAK,UAAU;EACjB;EAEA,YAAY;GACV,KAAK,OAAO,IAAI;GAChB,IAAI,QAAQ,UAAU,YAAY,UAAU,CAAC,KAAK,MAAM,OAAO;EACjE;CACF;CAEA,OAAO;AACT"}
|
package/dist/tabs.cjs
CHANGED
|
@@ -67,7 +67,6 @@ function createTabsWebSocket(options = {}) {
|
|
|
67
67
|
}
|
|
68
68
|
};
|
|
69
69
|
const live = /* @__PURE__ */ new Set();
|
|
70
|
-
let hiding = false;
|
|
71
70
|
const onPageHide = () => {
|
|
72
71
|
for (const leave of [...live]) leave();
|
|
73
72
|
};
|
|
@@ -175,7 +174,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
175
174
|
}
|
|
176
175
|
}
|
|
177
176
|
}
|
|
178
|
-
|
|
177
|
+
const self = {
|
|
179
178
|
channel,
|
|
180
179
|
stop() {
|
|
181
180
|
clearTimeout(lingerTimer);
|
|
@@ -186,9 +185,10 @@ function createTabsWebSocket(options = {}) {
|
|
|
186
185
|
}
|
|
187
186
|
release?.();
|
|
188
187
|
}
|
|
189
|
-
}
|
|
188
|
+
};
|
|
189
|
+
agents.set(key, self);
|
|
190
190
|
navigator.locks.request(key, () => {
|
|
191
|
-
if (
|
|
191
|
+
if (agents.get(key) !== self) return;
|
|
192
192
|
channel.onmessage = (event) => handle(event.data);
|
|
193
193
|
post({ t: "leader" });
|
|
194
194
|
return new Promise((resolve) => release = resolve);
|
|
@@ -216,12 +216,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
216
216
|
#state = CONNECTING;
|
|
217
217
|
#channel;
|
|
218
218
|
#leave = () => {
|
|
219
|
-
if (this.#state
|
|
220
|
-
this.#post({
|
|
221
|
-
t: "disconnect",
|
|
222
|
-
id: this.#id
|
|
223
|
-
});
|
|
224
|
-
this.#end(1001, "", false);
|
|
219
|
+
if (this.#state < CLOSING) this.#end(1001, "", false);
|
|
225
220
|
};
|
|
226
221
|
#inner;
|
|
227
222
|
static dispose() {
|
|
@@ -256,10 +251,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
256
251
|
id: this.#id
|
|
257
252
|
});
|
|
258
253
|
live.add(this.#leave);
|
|
259
|
-
|
|
260
|
-
hiding = true;
|
|
261
|
-
addEventListener("pagehide", onPageHide);
|
|
262
|
-
}
|
|
254
|
+
addEventListener("pagehide", onPageHide);
|
|
263
255
|
}
|
|
264
256
|
get readyState() {
|
|
265
257
|
return this.#state;
|
|
@@ -322,9 +314,14 @@ function createTabsWebSocket(options = {}) {
|
|
|
322
314
|
}
|
|
323
315
|
#end(code, reason, wasClean) {
|
|
324
316
|
if (this.#state === CLOSED) return;
|
|
317
|
+
if (this.#state < CLOSING) this.#post({
|
|
318
|
+
t: "disconnect",
|
|
319
|
+
id: this.#id
|
|
320
|
+
});
|
|
325
321
|
this.#state = CLOSED;
|
|
326
322
|
this.#channel?.close();
|
|
327
323
|
live.delete(this.#leave);
|
|
324
|
+
if (!live.size) removeEventListener("pagehide", onPageHide);
|
|
328
325
|
this.dispatchEvent(closeEvent(code, reason, wasClean));
|
|
329
326
|
}
|
|
330
327
|
}
|
package/dist/tabs.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabs.cjs","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n let hiding = false;\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n agents.set(key, {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n });\n void navigator.locks.request(key, () => {\n if (!agents.has(key)) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again.\n #leave = () => {\n if (this.#state >= CLOSING) return; // `close()` told the leader already\n this.#post({ t: 'disconnect', id: this.#id });\n this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n if (!hiding) {\n hiding = true;\n addEventListener('pagehide', onPageHide);\n }\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"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ACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"tabs.cjs","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n const self = {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n };\n agents.set(key, self);\n void navigator.locks.request(key, () => {\n // Stopped by `dispose()`, even if the URL has a new agent in this tab since.\n if (agents.get(key) !== self) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again. After `close()`, it ends by itself.\n #leave = () => {\n if (this.#state < CLOSING) this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n // While any socket is live; adding it again does nothing.\n addEventListener('pagehide', onPageHide);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n // Not through `close()`: tell the leader, which may count this socket still, such as one\n // it heard from only after the shared socket closed.\n if (this.#state < CLOSING) this.#post({ t: 'disconnect', id: this.#id });\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n if (!live.size) removeEventListener('pagehide', onPageHide);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";;AAyDA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAYf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,IAAI,MAAM;AAGV,MAAM,SAAS,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCtB,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,SAAS,QAAQ,UAAU;CAEjC,MAAM,yBAAS,IAAI,IAA6D;CAEhF,MAAM,QAAQ,SAAkB;EAC9B,IAAI,CAAC,QAAQ,QAAQ,OAAO,SAAS,UAAU,OAAO;EACtD,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,QAAQ;GACN,OAAO;EACT;CACF;;CAGA,MAAM,WACJ,WACA,YACG;EACH,IAAI,CAAC,aAAa,YAAY,QAAQ,OAAO,KAAA;EAC7C,IAAI;GACF,OAAO,UAAU,OAAO,KAAK,KAAA;EAC/B,QAAQ;GACN;EACF;CACF;CAIA,MAAM,uBAAO,IAAI,IAAgB;CACjC,MAAM,mBAAmB;EACvB,KAAK,MAAM,SAAS,CAAC,GAAG,IAAI,GAAG,MAAM;CACvC;CAEA,SAAS,MAAM,KAAa,KAAa,WAA0C;EACjF,IAAI,OAAO,IAAI,GAAG,GAAG;EACrB,MAA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AI,KAAK,WAAW,QAAQ;GAG5B,IAAI,KAAK,SAAS,SAAS,KAAK,MAAM;IAAE,GAAG;IAAc,IAAI,KAAK;GAAI,CAAC;GACvE,KAAK,SAAS;GACd,KAAK,UAAU,MAAM;GACrB,KAAK,OAAO,KAAK,MAAM;GACvB,IAAI,CAAC,KAAK,MAAM,oBAAoB,YAAY,UAAU;GAC1D,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/dist/tabs.js
CHANGED
|
@@ -66,7 +66,6 @@ function createTabsWebSocket(options = {}) {
|
|
|
66
66
|
}
|
|
67
67
|
};
|
|
68
68
|
const live = /* @__PURE__ */ new Set();
|
|
69
|
-
let hiding = false;
|
|
70
69
|
const onPageHide = () => {
|
|
71
70
|
for (const leave of [...live]) leave();
|
|
72
71
|
};
|
|
@@ -174,7 +173,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
174
173
|
}
|
|
175
174
|
}
|
|
176
175
|
}
|
|
177
|
-
|
|
176
|
+
const self = {
|
|
178
177
|
channel,
|
|
179
178
|
stop() {
|
|
180
179
|
clearTimeout(lingerTimer);
|
|
@@ -185,9 +184,10 @@ function createTabsWebSocket(options = {}) {
|
|
|
185
184
|
}
|
|
186
185
|
release?.();
|
|
187
186
|
}
|
|
188
|
-
}
|
|
187
|
+
};
|
|
188
|
+
agents.set(key, self);
|
|
189
189
|
navigator.locks.request(key, () => {
|
|
190
|
-
if (
|
|
190
|
+
if (agents.get(key) !== self) return;
|
|
191
191
|
channel.onmessage = (event) => handle(event.data);
|
|
192
192
|
post({ t: "leader" });
|
|
193
193
|
return new Promise((resolve) => release = resolve);
|
|
@@ -215,12 +215,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
215
215
|
#state = CONNECTING;
|
|
216
216
|
#channel;
|
|
217
217
|
#leave = () => {
|
|
218
|
-
if (this.#state
|
|
219
|
-
this.#post({
|
|
220
|
-
t: "disconnect",
|
|
221
|
-
id: this.#id
|
|
222
|
-
});
|
|
223
|
-
this.#end(1001, "", false);
|
|
218
|
+
if (this.#state < CLOSING) this.#end(1001, "", false);
|
|
224
219
|
};
|
|
225
220
|
#inner;
|
|
226
221
|
static dispose() {
|
|
@@ -255,10 +250,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
255
250
|
id: this.#id
|
|
256
251
|
});
|
|
257
252
|
live.add(this.#leave);
|
|
258
|
-
|
|
259
|
-
hiding = true;
|
|
260
|
-
addEventListener("pagehide", onPageHide);
|
|
261
|
-
}
|
|
253
|
+
addEventListener("pagehide", onPageHide);
|
|
262
254
|
}
|
|
263
255
|
get readyState() {
|
|
264
256
|
return this.#state;
|
|
@@ -321,9 +313,14 @@ function createTabsWebSocket(options = {}) {
|
|
|
321
313
|
}
|
|
322
314
|
#end(code, reason, wasClean) {
|
|
323
315
|
if (this.#state === CLOSED) return;
|
|
316
|
+
if (this.#state < CLOSING) this.#post({
|
|
317
|
+
t: "disconnect",
|
|
318
|
+
id: this.#id
|
|
319
|
+
});
|
|
324
320
|
this.#state = CLOSED;
|
|
325
321
|
this.#channel?.close();
|
|
326
322
|
live.delete(this.#leave);
|
|
323
|
+
if (!live.size) removeEventListener("pagehide", onPageHide);
|
|
327
324
|
this.dispatchEvent(closeEvent(code, reason, wasClean));
|
|
328
325
|
}
|
|
329
326
|
}
|
package/dist/tabs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabs.js","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n let hiding = false;\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n agents.set(key, {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n });\n void navigator.locks.request(key, () => {\n if (!agents.has(key)) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again.\n #leave = () => {\n if (this.#state >= CLOSING) return; // `close()` told the leader already\n this.#post({ t: 'disconnect', id: this.#id });\n this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n if (!hiding) {\n hiding = true;\n addEventListener('pagehide', onPageHide);\n }\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings":";AAyDA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAYf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAA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AClB;QAAA,CAAC,OAAO,MAAM,OAAO,GAAG,SAAS,KAAK,GAAG,GAAG,KAAK,SAAS,OAAO,IAAI;GAAA,OACpE,IAAI,OAAO,MAAM,SAAS;IAC/B,IAAI,KAAK,WAAW,YAAY,KAAK,KAAK,OAAO,MAAM,OAAO,QAAQ,OAAO,QAAQ;SAChF;KAEH,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;KACrC,KAAK,KAAK,OAAO,MAAM,OAAO,QAAQ,KAAK;IAC7C;GACF,OAAO,IAAI,OAAO,MAAM,UAAU;IAEhC,IAAI,KAAK,WAAW,YAAY,KAAK,MAAM;KAAE,GAAG;KAAW,IAAI,KAAK;IAAI,CAAC;SACpE,KAAK,KAAK,MAAM,IAAI,KAAK;GAChC;EACF;EAEA,MAAM,UAAkB;GACtB,KAAK,SAAS;GACd,KAAK,WAAW;GAChB,KAAK,cAAc,IAAI,MAAM,MAAM,CAAC;EACtC;EAEA,SAAS,MAAe;GACtB,IAAI,KAAK,WAAW,MAAM;GAC1B,IAAI,gBAAgB,eAAe,KAAK,eAAe,QAAQ,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC;GACrF,KAAK,cAAc,IAAI,aAAa,WAAW,EAAE,KAAK,CAAC,CAAC;EAC1D;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,UAAU,MAAM;GACrB,KAAK,OAAO,KAAK,MAAM;GACvB,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"tabs.js","names":[],"sources":["../src/tabs.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/**\n * Recognize topic subscriptions, so tabs sharing a socket don't unsubscribe each other. With\n * `json`, only messages that parse are passed to these, and one that throws counts as\n * `undefined`, so heartbeat pings and other plain strings go through.\n */\nexport interface TabsTopics {\n /** The topic an outgoing message subscribes to, or `undefined`. */\n subscribe: (message: any) => string | null | undefined;\n /** The topic an outgoing message unsubscribes from, or `undefined`. */\n unsubscribe: (message: any) => string | null | undefined;\n /**\n * The topic of an incoming message, to deliver it only to the tabs that hold that topic.\n * Without it, every tab gets every message.\n */\n topic?: (message: any) => string | null | undefined;\n}\n\n/** Options for {@link createTabsWebSocket}. */\nexport interface TabsWebSocketOptions {\n /** The `WebSocket` the leading tab opens. Defaults to the global one. */\n WebSocket?: typeof WebSocket;\n /** Messages are JSON: the `topics` functions get them parsed. */\n json?: boolean;\n /** Share topic subscriptions between tabs. See {@link TabsTopics}. */\n topics?: TabsTopics;\n /**\n * How long the leading tab keeps the shared socket open after the last tab using it lets go,\n * in ms, so a reload doesn't close and reopen it.\n * @default 1000\n */\n linger?: number;\n /**\n * Who is signed in, such as the user's id. Tabs share a connection only with tabs that return\n * the same value, so when another user signs in, `close()` and then `connect()` open a\n * connection of their own instead of joining the one the previous user authenticated. Read\n * for every new socket.\n */\n session?: () => string | null | undefined;\n}\n\n/** The class from {@link createTabsWebSocket}: a `WebSocket`, plus a way to stop sharing. */\nexport interface TabsWebSocket {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n /**\n * Stop leading and listening in this tab: close the shared sockets it holds and let another\n * tab take over. For tests and hot module reloading; a closed tab does this by itself.\n */\n dispose(): void;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/** What tabs say to each other over the channel. */\ntype Signal =\n | { t: 'connect'; id: string }\n | { t: 'send'; id: string; data: unknown }\n | { t: 'disconnect'; id: string }\n | { t: 'open'; id: string; protocol: string }\n | { t: 'message'; data: unknown; to?: string[] }\n | { t: 'close'; code: number; reason: string; wasClean: boolean }\n | { t: 'leader' };\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nlet ids = 0;\n\n// What `read()` returns for a message that isn't JSON.\nconst UNREAD = Symbol();\n\n/**\n * Share one WebSocket between all the tabs of an app. Pass the returned class as the\n * `WebSocket` option: every tab keeps its own client, with its own reconnects, queue, topics and\n * hooks, but only one tab, the leader, opens a connection to the server. The others reach it\n * through a `BroadcastChannel`. Users with ten tabs open cost the server one connection, not ten.\n *\n * - The leader is elected with the Web Locks API. When its tab closes, another tab takes over,\n * and every tab's client reconnects through it.\n * - Each tab's sends go out on the shared socket. Every message from the server reaches every\n * tab, or, with `topics`, only the tabs that hold its topic.\n * - With `topics`, an unsubscribe goes to the server only when no other tab still holds the topic.\n *\n * Where `BroadcastChannel` or the Web Locks API is missing, each tab opens its own socket, as\n * without this.\n *\n * @example\n * ```ts\n * import { createTabsWebSocket } from 'react-websocket/tabs';\n *\n * export const live = createWebSocket(url, {\n * json: true,\n * WebSocket: createTabsWebSocket({\n * json: true,\n * topics: {\n * subscribe: message => (message.type === 'subscribe' ? message.topic : undefined),\n * unsubscribe: message => (message.type === 'unsubscribe' ? message.topic : undefined),\n * topic: message => message.topic\n * }\n * })\n * });\n * ```\n */\nexport function createTabsWebSocket(options: TabsWebSocketOptions = {}): TabsWebSocket {\n const linger = options.linger ?? 1000;\n // One per URL in this tab: it waits to lead, and leads while it holds the lock.\n const agents = new Map<string, { channel: BroadcastChannel; stop: () => void }>();\n\n const read = (data: unknown) => {\n if (!options.json || typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return UNREAD;\n }\n };\n\n /** A topic `recognize` finds in `data`, if it parses and `recognize` doesn't throw. */\n const topicOf = (\n recognize: ((message: any) => string | null | undefined) | undefined,\n message: unknown\n ) => {\n if (!recognize || message === UNREAD) return undefined;\n try {\n return recognize(message) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n // The sockets this tab has on shared ones. A tab that goes away tells the leading tab,\n // which would otherwise keep their topics and the shared socket for them.\n const live = new Set<() => void>();\n const onPageHide = () => {\n for (const leave of [...live]) leave();\n };\n\n function agent(key: string, url: string, protocols: string | string[] | undefined) {\n if (agents.has(key)) return;\n const channel = new BroadcastChannel(key);\n const post = (signal: Signal) => channel.postMessage(signal);\n let real: WebSocket | undefined;\n // The tabs' sockets on the shared one, and whether each has been told it's open.\n const clients = new Map<string, boolean>();\n // Who holds each topic, so an unsubscribe waits for the last one.\n const holders = new Map<string, Set<string>>();\n let lingerTimer: ReturnType<typeof setTimeout> | undefined;\n let release: (() => void) | undefined;\n\n function opened(id: string) {\n clients.set(id, true);\n post({ t: 'open', id, protocol: real!.protocol });\n }\n\n function connect() {\n if (real) return;\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n let socket: WebSocket;\n try {\n socket = real = new Impl(url, protocols);\n } catch {\n clients.clear();\n return post({ t: 'close', code: 1006, reason: '', wasClean: false });\n }\n socket.binaryType = 'arraybuffer';\n socket.onopen = () => {\n for (const [id, told] of clients) if (!told) opened(id);\n };\n socket.onmessage = event => {\n const topic = topicOf(options.topics?.topic, read(event.data));\n if (topic === undefined) return post({ t: 'message', data: event.data });\n const to = [...(holders.get(topic) ?? [])];\n if (to.length) post({ t: 'message', data: event.data, to });\n };\n socket.onerror = () => {};\n socket.onclose = event => {\n if (real !== socket) return;\n real = undefined;\n clients.clear();\n holders.clear();\n post({ t: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function send(id: string, data: unknown) {\n const { topics } = options;\n if (topics) {\n const message = read(data);\n const subscribed = topicOf(topics.subscribe, message);\n if (subscribed !== undefined) {\n if (!holders.has(subscribed)) holders.set(subscribed, new Set());\n holders.get(subscribed)!.add(id);\n }\n const unsubscribed = topicOf(topics.unsubscribe, message);\n if (unsubscribed !== undefined) {\n const set = holders.get(unsubscribed);\n set?.delete(id);\n if (set?.size) return; // another tab still holds it\n holders.delete(unsubscribed);\n }\n }\n if (real?.readyState === OPEN) real.send(data as Parameters<WebSocket['send']>[0]);\n }\n\n function handle(signal: Signal) {\n if (signal.t === 'connect') {\n clearTimeout(lingerTimer);\n clients.set(signal.id, false);\n connect();\n if (real?.readyState === OPEN) opened(signal.id);\n } else if (signal.t === 'send') {\n if (clients.get(signal.id)) send(signal.id, signal.data);\n } else if (signal.t === 'disconnect') {\n clients.delete(signal.id);\n for (const set of holders.values()) set.delete(signal.id);\n if (!clients.size) {\n clearTimeout(lingerTimer);\n lingerTimer = setTimeout(() => {\n if (clients.size || !real) return;\n // Forget it first: a tab connecting while it closes gets a new one.\n const socket = real;\n real = undefined;\n socket.close(1000);\n }, linger);\n }\n }\n }\n\n const self = {\n channel,\n stop() {\n clearTimeout(lingerTimer);\n channel.close();\n if (real) {\n real.onclose = null;\n real.close(1000);\n }\n release?.();\n }\n };\n agents.set(key, self);\n void navigator.locks.request(key, () => {\n // Stopped by `dispose()`, even if the URL has a new agent in this tab since.\n if (agents.get(key) !== self) return;\n channel.onmessage = event => handle(event.data as Signal);\n // Sockets that were using the tab that led before start over with this one.\n post({ t: 'leader' });\n // Lead until this tab goes away, or `dispose()`.\n return new Promise<void>(resolve => (release = resolve));\n });\n }\n\n const Fallback = options.WebSocket;\n\n class TabSocket extends EventTarget implements WebSocket {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n binaryType: BinaryType = 'blob';\n protocol = '';\n\n #id = `${Date.now().toString(36)}-${++ids}-${Math.random().toString(36).slice(2)}`;\n #state: WebSocket['readyState'] = CONNECTING;\n #channel: BroadcastChannel | undefined;\n // The page is going away, or into the back/forward cache: let go of the shared socket, and\n // close, so a page that comes back connects again. After `close()`, it ends by itself.\n #leave = () => {\n if (this.#state < CLOSING) this.#end(1001, '', false);\n };\n // Without `BroadcastChannel` or locks: a socket of this tab's own.\n #inner: WebSocket | undefined;\n\n static dispose() {\n for (const { stop } of agents.values()) stop();\n agents.clear();\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/tabs: no WebSocket here (server render?)');\n }\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n this.url = String(url);\n if (typeof BroadcastChannel === 'undefined' || !globalThis.navigator?.locks) {\n const inner = (this.#inner = new (Fallback ?? globalThis.WebSocket)(url, protocols));\n // As from the leading tab: `#message` turns it into what `binaryType` asks for.\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => this.#open(inner.protocol);\n inner.onmessage = event => this.#message(event.data);\n inner.onerror = () => this.dispatchEvent(new Event('error'));\n inner.onclose = event => this.#end(event.code, event.reason, event.wasClean);\n return;\n }\n // The session goes first: Node routes channel messages by the name up to a NUL.\n const session = options.session\n ? `session=${encodeURIComponent(options.session() ?? '')}:`\n : '';\n const key = `react-websocket-tabs:${session}${this.url}\\u0000${JSON.stringify(protocols ?? null)}`;\n agent(key, this.url, protocols);\n const channel = (this.#channel = new BroadcastChannel(key));\n channel.onmessage = event => this.#signal(event.data as Signal);\n this.#post({ t: 'connect', id: this.#id });\n live.add(this.#leave);\n // While any socket is live; adding it again does nothing.\n addEventListener('pagehide', onPageHide);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? 0;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.#state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.#state !== OPEN) return;\n if (this.#inner) this.#inner.send(data);\n else this.#post({ t: 'send', id: this.#id, data });\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n if (this.#inner) this.#inner.close(code, reason);\n this.#state = CLOSING;\n if (this.#inner) return;\n // Only this tab's socket closes; the shared one stays for the others.\n this.#post({ t: 'disconnect', id: this.#id });\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #post(signal: Signal) {\n this.#channel?.postMessage(signal);\n }\n\n #signal(signal: Signal) {\n if (signal.t === 'open') {\n if (signal.id === this.#id && this.#state === CONNECTING) this.#open(signal.protocol);\n } else if (signal.t === 'message') {\n if (!signal.to || signal.to.includes(this.#id)) this.#message(signal.data);\n } else if (signal.t === 'close') {\n if (this.#state !== CONNECTING) this.#end(signal.code, signal.reason, signal.wasClean);\n else {\n // The shared socket failed before this one opened.\n this.dispatchEvent(new Event('error'));\n this.#end(signal.code, signal.reason, false);\n }\n } else if (signal.t === 'leader') {\n // A new leading tab: start over with it, or ask it to connect us.\n if (this.#state === CONNECTING) this.#post({ t: 'connect', id: this.#id });\n else this.#end(1006, '', false);\n }\n }\n\n #open(protocol: string) {\n this.#state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n #message(data: unknown) {\n if (this.#state !== OPEN) return;\n if (data instanceof ArrayBuffer && this.binaryType === 'blob') data = new Blob([data]);\n this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n #end(code: number, reason: string, wasClean: boolean) {\n if (this.#state === CLOSED) return;\n // Not through `close()`: tell the leader, which may count this socket still, such as one\n // it heard from only after the shared socket closed.\n if (this.#state < CLOSING) this.#post({ t: 'disconnect', id: this.#id });\n this.#state = CLOSED;\n this.#channel?.close();\n live.delete(this.#leave);\n if (!live.size) removeEventListener('pagehide', onPageHide);\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return TabSocket as unknown as TabsWebSocket;\n}\n"],"mappings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AAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/dist/timeline.cjs
CHANGED
|
@@ -40,6 +40,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
40
40
|
let arrival = -Infinity;
|
|
41
41
|
let rendered = -Infinity;
|
|
42
42
|
let stale = false;
|
|
43
|
+
let measuredBefore;
|
|
43
44
|
let seq = 0;
|
|
44
45
|
let pending = [];
|
|
45
46
|
let prediction;
|
|
@@ -71,7 +72,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
71
72
|
function renderTime() {
|
|
72
73
|
if (!buffer.length) return;
|
|
73
74
|
const measured = latency?.getSnapshot();
|
|
74
|
-
const edge = measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
75
|
+
const edge = measured !== measuredBefore && measured?.offset !== void 0 && measured.rtt !== void 0 ? latency.serverNow() - measured.rtt / 2 : performance.now() + arrival;
|
|
75
76
|
rendered = Math.max(rendered, edge - (typeof delay === "function" ? delay() : delay));
|
|
76
77
|
return rendered;
|
|
77
78
|
}
|
|
@@ -110,6 +111,7 @@ function createWebSocketTimeline(client, options) {
|
|
|
110
111
|
pending = [];
|
|
111
112
|
folded = -1;
|
|
112
113
|
stale = true;
|
|
114
|
+
measuredBefore = latency?.getSnapshot();
|
|
113
115
|
}), client.on("message", (message) => {
|
|
114
116
|
const snapshot = options.snapshot(message);
|
|
115
117
|
if (snapshot != null) receive(snapshot);
|
package/dist/timeline.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeline.cjs","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time, the\n * server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";;AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,MAAM,EAAE,aAAa,SAAS,OAAO,WAAW;CAChD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,OAAO,KAAK,IAAI,GAAG,QAAQ,UAAU,EAAE;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAGtC,IAAI,SAA+D,CAAC;CAEpE,IAAI,UAAU;CAEd,IAAI,WAAW;CAEf,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,IAAI,UAAuC,CAAC;CAC5C,IAAI;CAEJ,IAAI,SAAS;CAEb,SAAS,SAAS;EAChB,KAAK,MAAM,YAAY,CAAC,GAAG,SAAS,GAAG,SAAS;CAClD;CAEA,SAAS,QAAQ;EACf,SAAS,CAAC;EACV,UAAU,WAAW;EACrB,QAAQ;CACV;CAEA,SAAS,QAAQ,UAA+B;EAC9C,IAAI,OAAO,MAAM;EACjB,MAAM,SAAS,OAAO,GAAG,EAAE;EAE3B,IAAI,UAAU,SAAS,QAAQ,OAAO,SAAS,MAAM;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R,KAAK,SAAQ,QAAO,IAAI,CAAC;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"timeline.cjs","names":[],"sources":["../src/timeline.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient, WebSocketLatency } from './core';\n\n/** A server snapshot, as returned by the `snapshot` option. */\nexport interface TimelineSnapshot<S> {\n /** Server time the state is for, in ms. Must increase from one snapshot to the next. */\n readonly time: number;\n /** The authoritative state at `time`. */\n readonly state: S;\n /**\n * `seq` of the last input from this client that the server applied before taking the\n * snapshot. Inputs up to it are confirmed and no longer predicted. Omit it to keep the\n * previous one.\n */\n readonly ack?: number;\n}\n\n/** Client-side prediction for your own inputs. See {@link WebSocketTimelineOptions.input}. */\nexport interface TimelineInputOptions<S, I, Out> {\n /**\n * Build the message for an input, tagged with its `seq`. Annotate `input`: that's what\n * `timeline.input()` accepts. Sent with `volatile`, so inputs are never replayed late.\n */\n send: (input: I, seq: number) => Out;\n /**\n * Apply one input to a state, exactly as the server does. Must be pure: return a new state\n * instead of changing `state`, which is a snapshot from the server.\n */\n predict: (state: S, input: I) => S;\n /**\n * Drop an input instead of sending it while more than this many bytes are already waiting in\n * the browser's send buffer (see `SendOptions.maxBuffered`). For input sent every tick on a\n * slow link. A dropped input isn't predicted.\n */\n maxBuffered?: number;\n}\n\n/** Options for {@link createWebSocketTimeline}. */\nexport interface WebSocketTimelineOptions<S, I, In, Out> {\n /** Recognize a snapshot. Return `undefined` (or `null`) for any other message. */\n snapshot: (message: In) => TimelineSnapshot<S> | null | undefined;\n /**\n * Blend two states. `t` runs from 0 (`from`) to 1 (`to`), and above 1 only when\n * extrapolating. Without it, `at()` steps from one snapshot to the next.\n */\n interpolate?: (from: S, to: S, t: number) => S;\n /**\n * How far behind the newest snapshot to render, in ms: enough to cover the snapshot\n * interval plus jitter, so there are usually two snapshots to blend between. A function is\n * read on every call, for a delay that adapts.\n * @default 100\n */\n delay?: number | (() => number);\n /**\n * How far past the newest snapshot `at()` may extrapolate when the next one is late, in ms.\n * Needs `interpolate`. `0` holds the newest state instead.\n * @default 0\n */\n extrapolate?: number;\n /**\n * How many snapshots to keep (at least 2).\n * @default 30\n */\n buffer?: number;\n /**\n * Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use\n * the same clock as snapshot `time`. Without it, or before the first pong with a time on the\n * current connection, the server clock is estimated from when snapshots arrive.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;\n /** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */\n input?: TimelineInputOptions<S, I, Out>;\n}\n\n/** Server snapshots on a timeline, with your own inputs predicted on top. Create with {@link createWebSocketTimeline}. */\nexport interface WebSocketTimeline<S, I> {\n /** The client whose snapshots this timeline keeps. */\n readonly client: WebSocketClient<any, any>;\n /**\n * The state at `time` (by default `renderTime()`), interpolated between the snapshots around\n * it. For what the server moves, such as other players. `undefined` before any snapshot.\n */\n at(time?: number): S | undefined;\n /**\n * The newest snapshot with your unconfirmed inputs replayed on top. For what your inputs\n * move, such as your own player. Cached, so it's cheap to call every frame.\n */\n predicted(): S | undefined;\n /**\n * Send an input and predict it. Returns its `seq`, or `undefined` if it couldn't be sent\n * (the socket isn't open, or `maxBuffered` dropped it), in which case it isn't predicted.\n */\n input(input: I): number | undefined;\n /** The newest snapshot, as `snapshot` returned it. */\n latest(): TimelineSnapshot<S> | undefined;\n /**\n * The server time `at()` renders by default: the newest snapshot's time, give or take, minus\n * `delay`. It never goes backward until the timeline starts over. `undefined` before any snapshot.\n */\n renderTime(): number | undefined;\n /** How many inputs were sent but not confirmed yet. */\n pending(): number;\n /**\n * Called after each new snapshot and on `reset()`. Compatible with `useSyncExternalStore` for\n * `latest` and `pending`, but not for `at`, `predicted` or `renderTime`, which change with time.\n */\n subscribe(listener: () => void): () => void;\n /** Forget all snapshots and pending inputs now. `seq` keeps counting. */\n reset(): void;\n /** Stop listening. Only needed for timelines created dynamically. */\n dispose(): void;\n}\n\n// Unconfirmed inputs kept at most. A server that stops confirming would otherwise make every\n// snapshot replay a growing list.\nconst MAX_PENDING = 1000;\n\n/**\n * Keep server snapshots on a timeline for multiplayer games: render what the server moves\n * slightly in the past, interpolated between snapshots, and what your inputs move right away,\n * predicted and corrected when the server confirms them.\n *\n * Read it once per frame (in `requestAnimationFrame` or React Three Fiber's `useFrame`): `at()`\n * for everyone else, `predicted()` for you. It listens from creation, starts over on reconnect,\n * and doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * import { createWebSocketTimeline } from 'react-websocket/timeline';\n *\n * export const timeline = createWebSocketTimeline(game, {\n * snapshot: m => (m.type === 'snapshot' ? { time: m.time, ack: m.ack, state: m.world } : undefined),\n * interpolate: (from, to, t) => lerpWorld(from, to, t),\n * latency,\n * input: {\n * send: (input: Move, seq) => ({ type: 'input', seq, ...input }),\n * predict: (world, input) => move(world, me, input)\n * }\n * });\n *\n * // Every frame:\n * draw(timeline.at(), timeline.predicted());\n * // On a key press:\n * timeline.input({ dx: 1, dy: 0 });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only. `S` comes from `snapshot`, and\n// `I` from how `input.send` annotates its parameter (`never` without `input`).\nexport function createWebSocketTimeline<In, const Out, S, I = never>(\n client: WebSocketClient<In, Out>,\n options: WebSocketTimelineOptions<S, I, NoInfer<In>, NoInfer<Out>>\n): WebSocketTimeline<S, I> {\n const { interpolate, latency, input: inputs } = options;\n const delay = options.delay ?? 100;\n const extrapolate = options.extrapolate ?? 0;\n const keep = Math.max(2, options.buffer ?? 30);\n const listeners = new Set<() => void>();\n\n // Oldest first, `time` strictly increasing. `arrived` is `performance.now()` on receipt.\n let buffer: { snapshot: TimelineSnapshot<S>; arrived: number }[] = [];\n // Server time minus `performance.now()`, from the least delayed snapshot in the buffer.\n let arrival = -Infinity;\n // The last render time handed out, so that it never goes backward.\n let rendered = -Infinity;\n // A new connection opened: its first snapshot replaces the buffer.\n let stale = false;\n // What `latency` measured before the current connection opened: the clock of a server that\n // may have restarted since.\n let measuredBefore: unknown;\n let seq = 0;\n let pending: { seq: number; input: I }[] = [];\n let prediction: S | undefined;\n // How many pending inputs `prediction` includes. `-1`: start again from the newest snapshot.\n let folded = -1;\n\n function notify() {\n for (const listener of [...listeners]) listener();\n }\n\n function clear() {\n buffer = [];\n arrival = rendered = -Infinity;\n stale = false;\n }\n\n function receive(snapshot: TimelineSnapshot<S>) {\n if (stale) clear();\n const newest = buffer.at(-1);\n // A WebSocket keeps order, so this is a duplicate or a server clock that stepped back.\n if (newest && snapshot.time <= newest.snapshot.time) return;\n buffer.push({ snapshot, arrived: performance.now() });\n if (buffer.length > keep) buffer.shift();\n arrival = -Infinity;\n for (const entry of buffer) arrival = Math.max(arrival, entry.snapshot.time - entry.arrived);\n const { ack } = snapshot;\n if (ack != null) pending = pending.filter(entry => entry.seq > ack);\n folded = -1;\n notify();\n }\n\n function renderTime() {\n if (!buffer.length) return;\n const measured = latency?.getSnapshot();\n // The server time of a snapshot arriving now: half a round trip behind the server's clock.\n const edge =\n measured !== measuredBefore && measured?.offset !== undefined && measured.rtt !== undefined\n ? latency!.serverNow() - measured.rtt / 2\n : performance.now() + arrival;\n rendered = Math.max(rendered, edge - (typeof delay === 'function' ? delay() : delay));\n return rendered;\n }\n\n function at(time?: number): S | undefined {\n const n = buffer.length;\n if (!n) return;\n const t = time ?? renderTime()!;\n const last = buffer[n - 1]!.snapshot;\n if (t >= last.time) {\n const previous = buffer[n - 2]?.snapshot;\n if (!previous || !interpolate || !extrapolate || t === last.time) return last.state;\n const capped = Math.min(t, last.time + extrapolate);\n return interpolate(\n previous.state,\n last.state,\n (capped - previous.time) / (last.time - previous.time)\n );\n }\n // Reads are usually near the newest snapshot, so search from the end.\n let i = n - 2;\n while (i >= 0 && buffer[i]!.snapshot.time > t) i--;\n if (i < 0) return buffer[0]!.snapshot.state;\n const from = buffer[i]!.snapshot;\n const to = buffer[i + 1]!.snapshot;\n return !interpolate || t === from.time\n ? from.state\n : interpolate(from.state, to.state, (t - from.time) / (to.time - from.time));\n }\n\n function predicted(): S | undefined {\n const newest = buffer.at(-1);\n if (!newest) return;\n if (folded < 0) {\n prediction = newest.snapshot.state;\n folded = 0;\n }\n // Usually zero or one new input per frame; all of them once after each snapshot.\n while (folded < pending.length) {\n prediction = inputs!.predict(prediction!, pending[folded]!.input);\n folded++; // after `predict`, so one that throws is retried rather than skipped\n }\n return prediction;\n }\n\n const offs = [\n // Inputs on the old connection will never be confirmed. Keep showing the old snapshots\n // until the new connection sends its first one.\n client.on('open', () => {\n pending = [];\n folded = -1;\n stale = true;\n measuredBefore = latency?.getSnapshot();\n }),\n // A `snapshot` that throws leaves the timeline unchanged; the client re-throws it asynchronously.\n client.on('message', message => {\n const snapshot = options.snapshot(message);\n if (snapshot != null) receive(snapshot);\n })\n ];\n\n return {\n client,\n at,\n predicted,\n input(value) {\n const next = seq + 1;\n // Recorded only once it's sent, so a dropped input never shows as a move the server didn't make.\n const message = inputs!.send(value, next);\n if (!client.send(message, { volatile: true, maxBuffered: inputs!.maxBuffered })) return;\n seq = next;\n pending.push({ seq, input: value });\n if (pending.length > MAX_PENDING) {\n pending.shift();\n folded = -1;\n }\n return seq;\n },\n latest: () => buffer.at(-1)?.snapshot,\n renderTime,\n pending: () => pending.length,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset() {\n clear();\n pending = [];\n folded = -1;\n notify();\n },\n dispose() {\n offs.forEach(off => off());\n }\n };\n}\n"],"mappings":";;AAmHA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCpB,SAAgB,wBACd,QACA,SACyB;CACzB,MAAM,EAAE,aAAa,SAAS,OAAO,WAAW;CAChD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,OAAO,KAAK,IAAI,GAAG,QAAQ,UAAU,EAAE;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAGtC,IAAI,SAA+D,C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,OAAO,IAAI;GACxC,IAAI,CAAC,OAAO,KAAK,SAAS;IAAE,UAAU;IAAM,aAAa,OAAQ;GAAY,CAAC,GAAG;GACjF,MAAM;GACN,QAAQ,KAAK;IAAE;IAAK,OAAO;GAAM,CAAC;GAClC,IAAI,QAAQ,SAAS,aAAa;IAChC,QAAQ,MAAM;IACd,SAAS;GACX;GACA,OAAO;EACT;EACA,cAAc,OAAO,GAAG,EAAE,CAAC,EAAE;EAC7B;EACA,eAAe,QAAQ;EACvB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,QAAQ;GACN,MAAM;GACN,UAAU,CAAC;GACX,SAAS;GACT,OAAO;EACT;EACA,UAAU;GACR,KAAK,SAAQ,QAAO,IAAI,CAAC;EAC3B;CACF;AACF"}
|
package/dist/timeline.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as WebSocketClient } from "./types-
|
|
1
|
+
import { t as WebSocketClient } from "./types-Bb3sBG8L.cjs";
|
|
2
2
|
//#region src/latency.d.ts
|
|
3
3
|
/** Latest latency measurements. A new object is created on every change. */
|
|
4
4
|
interface Latency {
|
|
@@ -88,8 +88,8 @@ export interface WebSocketTimelineOptions<S, I, In, Out> {
|
|
|
88
88
|
buffer?: number;
|
|
89
89
|
/**
|
|
90
90
|
* Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use
|
|
91
|
-
* the same clock as snapshot `time`. Without it, or before the first pong with a time
|
|
92
|
-
* server clock is estimated from when snapshots arrive.
|
|
91
|
+
* the same clock as snapshot `time`. Without it, or before the first pong with a time on the
|
|
92
|
+
* current connection, the server clock is estimated from when snapshots arrive.
|
|
93
93
|
*/
|
|
94
94
|
latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;
|
|
95
95
|
/** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */
|
package/dist/timeline.d.ts
CHANGED
|
@@ -61,8 +61,8 @@ export interface WebSocketTimelineOptions<S, I, In, Out> {
|
|
|
61
61
|
buffer?: number;
|
|
62
62
|
/**
|
|
63
63
|
* Take the server clock from `createWebSocketLatency` on the same client. Its pongs must use
|
|
64
|
-
* the same clock as snapshot `time`. Without it, or before the first pong with a time
|
|
65
|
-
* server clock is estimated from when snapshots arrive.
|
|
64
|
+
* the same clock as snapshot `time`. Without it, or before the first pong with a time on the
|
|
65
|
+
* current connection, the server clock is estimated from when snapshots arrive.
|
|
66
66
|
*/
|
|
67
67
|
latency?: Pick<WebSocketLatency, 'getSnapshot' | 'serverNow'>;
|
|
68
68
|
/** Send inputs tagged with a sequence number, and predict their effect until the server confirms them. */
|