react-websocket 4.22.1 → 4.22.3
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 +8 -9
- package/dist/ag-ui.cjs.map +1 -1
- package/dist/ag-ui.d.cts +3 -8
- package/dist/ag-ui.d.ts +0 -2
- package/dist/ag-ui.js +8 -9
- package/dist/ag-ui.js.map +1 -1
- package/dist/chaos.cjs +60 -13
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts +1 -2
- package/dist/chaos.d.ts +1 -2
- package/dist/chaos.js +60 -13
- package/dist/chaos.js.map +1 -1
- package/dist/core.cjs +93 -65
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +4 -25
- package/dist/core.d.ts +4 -25
- package/dist/core.js +93 -65
- package/dist/core.js.map +1 -1
- package/dist/devtools.cjs +1 -2
- package/dist/devtools.d.cts +0 -2
- package/dist/devtools.d.ts +0 -2
- package/dist/devtools.js +1 -2
- package/dist/index.cjs +1 -2
- package/dist/index.d.cts +4 -31
- package/dist/index.d.ts +3 -24
- package/dist/index.development.cjs +1 -2
- package/dist/index.development.js +1 -2
- package/dist/index.js +1 -2
- package/dist/outbox.cjs +15 -10
- package/dist/outbox.cjs.map +1 -1
- package/dist/outbox.d.cts +1 -3
- package/dist/outbox.d.ts +0 -2
- package/dist/outbox.js +15 -10
- package/dist/outbox.js.map +1 -1
- package/dist/replay.cjs +13 -9
- package/dist/replay.cjs.map +1 -1
- package/dist/replay.d.cts +8 -4
- package/dist/replay.d.ts +8 -4
- package/dist/replay.js +13 -9
- package/dist/replay.js.map +1 -1
- package/dist/tabs.cjs +12 -16
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs.d.cts +0 -2
- package/dist/tabs.d.ts +0 -2
- package/dist/tabs.js +12 -16
- package/dist/tabs.js.map +1 -1
- package/dist/timeline.cjs +4 -3
- package/dist/timeline.cjs.map +1 -1
- package/dist/timeline.d.cts +3 -7
- package/dist/timeline.d.ts +2 -4
- package/dist/timeline.js +4 -3
- package/dist/timeline.js.map +1 -1
- package/dist/{types-paLT8yQF.d.cts → types-DyZm2F7B.d.cts} +4 -5
- package/dist/webtransport.cjs +13 -12
- package/dist/webtransport.cjs.map +1 -1
- package/dist/webtransport.d.cts +0 -2
- package/dist/webtransport.d.ts +0 -2
- package/dist/webtransport.js +13 -12
- package/dist/webtransport.js.map +1 -1
- package/package.json +9 -9
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/types.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Where to connect: a URL, or a function that returns one (sync or async).
|
|
4
3
|
*
|
|
@@ -235,8 +234,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
235
234
|
close(code?: number, reason?: string): void;
|
|
236
235
|
/**
|
|
237
236
|
* Drop the current socket (if any) and connect again immediately, resetting the
|
|
238
|
-
* backoff. Also restarts a `closed` client
|
|
239
|
-
*
|
|
237
|
+
* backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
|
|
238
|
+
* again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
|
|
239
|
+
* are kept: when another user signs in, call `close()` and then `connect()` instead.
|
|
240
240
|
*/
|
|
241
241
|
reconnect(): void;
|
|
242
242
|
/**
|
|
@@ -268,6 +268,5 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
268
268
|
*/
|
|
269
269
|
acquire(): () => void;
|
|
270
270
|
}
|
|
271
|
-
//#endregion
|
|
272
271
|
export { WebSocketClient as t };
|
|
273
|
-
//# sourceMappingURL=types-
|
|
272
|
+
//# sourceMappingURL=types-DyZm2F7B.d.cts.map
|
package/dist/webtransport.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// src/webtransport.ts
|
|
3
3
|
const CONNECTING = 0;
|
|
4
4
|
const OPEN = 1;
|
|
5
5
|
const CLOSING = 2;
|
|
@@ -90,7 +90,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
90
90
|
this.#fallBack(protocols);
|
|
91
91
|
return;
|
|
92
92
|
}
|
|
93
|
-
this.#connect(protocols);
|
|
93
|
+
this.#connect(protocols).catch(() => this.#fail());
|
|
94
94
|
}
|
|
95
95
|
get readyState() {
|
|
96
96
|
return this.#state;
|
|
@@ -106,7 +106,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
106
106
|
const chain = (this.#chain ?? Promise.resolve()).then(async () => {
|
|
107
107
|
this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));
|
|
108
108
|
if (this.#chain === chain) this.#chain = void 0;
|
|
109
|
-
});
|
|
109
|
+
}).catch(() => this.#fail());
|
|
110
110
|
this.#chain = chain;
|
|
111
111
|
return;
|
|
112
112
|
}
|
|
@@ -141,6 +141,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
141
141
|
let timer;
|
|
142
142
|
try {
|
|
143
143
|
transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);
|
|
144
|
+
transport.closed.catch(() => {});
|
|
144
145
|
await Promise.race([transport.ready, new Promise((_, reject) => timer = setTimeout(reject, timeout, /* @__PURE__ */ new Error("timeout")))]);
|
|
145
146
|
const stream = await transport.createBidirectionalStream();
|
|
146
147
|
if (this.#state !== CONNECTING) return transport.close();
|
|
@@ -152,19 +153,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
152
153
|
this.#transport?.close();
|
|
153
154
|
this.#transport = void 0;
|
|
154
155
|
if (this.#state !== CONNECTING) return;
|
|
155
|
-
if (options.fallback === false)
|
|
156
|
-
this.dispatchEvent(new Event("error"));
|
|
157
|
-
return this.#end(1006, "", false);
|
|
158
|
-
}
|
|
156
|
+
if (options.fallback === false) return this.#fail();
|
|
159
157
|
fallingBack = true;
|
|
160
158
|
return this.#fallBack(protocols);
|
|
161
159
|
} finally {
|
|
162
160
|
clearTimeout(timer);
|
|
163
161
|
}
|
|
164
|
-
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () =>
|
|
165
|
-
this.dispatchEvent(new Event("error"));
|
|
166
|
-
this.#end(1006, "", false);
|
|
167
|
-
});
|
|
162
|
+
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () => this.#fail());
|
|
168
163
|
this.#state = OPEN;
|
|
169
164
|
this.dispatchEvent(new Event("open"));
|
|
170
165
|
}
|
|
@@ -229,6 +224,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
229
224
|
if (data instanceof ArrayBuffer && this.binaryType === "blob") data = new Blob([data]);
|
|
230
225
|
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
231
226
|
}
|
|
227
|
+
/** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */
|
|
228
|
+
#fail() {
|
|
229
|
+
if (this.#state === CLOSED) return;
|
|
230
|
+
this.#transport?.close();
|
|
231
|
+
this.dispatchEvent(new Event("error"));
|
|
232
|
+
this.#end(1006, "", false);
|
|
233
|
+
}
|
|
232
234
|
#end(code, reason, wasClean) {
|
|
233
235
|
if (this.#state === CLOSED) return;
|
|
234
236
|
this.#state = CLOSED;
|
|
@@ -237,7 +239,6 @@ function createWebTransportSocket(options = {}) {
|
|
|
237
239
|
}
|
|
238
240
|
return WebTransportSocket;
|
|
239
241
|
}
|
|
240
|
-
//#endregion
|
|
241
242
|
exports.createWebTransportSocket = createWebTransportSocket;
|
|
242
243
|
|
|
243
244
|
//# sourceMappingURL=webtransport.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webtransport.cjs","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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 bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n void this.#connect(protocols);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve()).then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n });\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) {\n this.dispatchEvent(new Event('error'));\n return this.#end(1006, '', false);\n }\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => {\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";;AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,MAA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,CAAC;MAC/B,IAAI,OAAO,aAAa,IAAI,QAAQ;MACpC,KAAK,OAAO,KAAK,SAAS,CAAC,GAAG,OAAO,MAAM,GAAG,IAAI,MAAM,CAAC;MACzD,SAAS,OAAO,MAAM,IAAI,MAAM;KAClC;IACF;GACF,QAAQ,CAER;EACF;EAEA,MAAM,eAAe,QAAiD;GACpE,IAAI;IACF,SAAS;KACP,MAAM,EAAE,OAAO,SAAS,MAAM,OAAO,KAAK;KAC1C,IAAI,MAAM;KACV,IAAI,MAAM,YAAY,KAAK,OAAO,MAAM,IAAK,MAAM,MAAM,CAAC,CAAC;IAC7D;GACF,QAAQ,CAER;EACF;EAEA,OAAO,MAAc,SAAqB;GACxC,KAAK,SAAS,SAAS,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM;EAClF;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,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"webtransport.cjs","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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 bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n // A fallback that throws, e.g. for protocols the WebSocket rejects, fails the connection.\n this.#connect(protocols).catch(() => this.#fail());\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve())\n .then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n })\n // A Blob that can't be read fails the connection, as in browsers, rather than\n // holding up every send after it.\n .catch(() => this.#fail());\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n // A session that fails rejects `closed` too, before anything listens to it.\n transport.closed.catch(() => {});\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) return this.#fail();\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => this.#fail()\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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 /** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */\n #fail() {\n if (this.#state === CLOSED) return;\n this.#transport?.close();\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n\n #end(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 return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";;AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,SAAS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src/webtransport.d.ts
|
|
2
1
|
/** Options for {@link createWebTransportSocket}. */
|
|
3
2
|
export interface WebTransportSocketOptions {
|
|
4
3
|
/**
|
|
@@ -63,5 +62,4 @@ export interface WebTransportWebSocket {
|
|
|
63
62
|
* ```
|
|
64
63
|
*/
|
|
65
64
|
export declare function createWebTransportSocket(options?: WebTransportSocketOptions): WebTransportWebSocket;
|
|
66
|
-
//#endregion
|
|
67
65
|
//# sourceMappingURL=webtransport.d.cts.map
|
package/dist/webtransport.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/webtransport.d.ts
|
|
2
1
|
/** Options for {@link createWebTransportSocket}. */
|
|
3
2
|
export interface WebTransportSocketOptions {
|
|
4
3
|
/**
|
|
@@ -63,5 +62,4 @@ export interface WebTransportWebSocket {
|
|
|
63
62
|
* ```
|
|
64
63
|
*/
|
|
65
64
|
export declare function createWebTransportSocket(options?: WebTransportSocketOptions): WebTransportWebSocket;
|
|
66
|
-
//#endregion
|
|
67
65
|
//# sourceMappingURL=webtransport.d.ts.map
|
package/dist/webtransport.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/webtransport.ts
|
|
2
2
|
const CONNECTING = 0;
|
|
3
3
|
const OPEN = 1;
|
|
4
4
|
const CLOSING = 2;
|
|
@@ -89,7 +89,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
89
89
|
this.#fallBack(protocols);
|
|
90
90
|
return;
|
|
91
91
|
}
|
|
92
|
-
this.#connect(protocols);
|
|
92
|
+
this.#connect(protocols).catch(() => this.#fail());
|
|
93
93
|
}
|
|
94
94
|
get readyState() {
|
|
95
95
|
return this.#state;
|
|
@@ -105,7 +105,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
105
105
|
const chain = (this.#chain ?? Promise.resolve()).then(async () => {
|
|
106
106
|
this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));
|
|
107
107
|
if (this.#chain === chain) this.#chain = void 0;
|
|
108
|
-
});
|
|
108
|
+
}).catch(() => this.#fail());
|
|
109
109
|
this.#chain = chain;
|
|
110
110
|
return;
|
|
111
111
|
}
|
|
@@ -140,6 +140,7 @@ function createWebTransportSocket(options = {}) {
|
|
|
140
140
|
let timer;
|
|
141
141
|
try {
|
|
142
142
|
transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);
|
|
143
|
+
transport.closed.catch(() => {});
|
|
143
144
|
await Promise.race([transport.ready, new Promise((_, reject) => timer = setTimeout(reject, timeout, /* @__PURE__ */ new Error("timeout")))]);
|
|
144
145
|
const stream = await transport.createBidirectionalStream();
|
|
145
146
|
if (this.#state !== CONNECTING) return transport.close();
|
|
@@ -151,19 +152,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
151
152
|
this.#transport?.close();
|
|
152
153
|
this.#transport = void 0;
|
|
153
154
|
if (this.#state !== CONNECTING) return;
|
|
154
|
-
if (options.fallback === false)
|
|
155
|
-
this.dispatchEvent(new Event("error"));
|
|
156
|
-
return this.#end(1006, "", false);
|
|
157
|
-
}
|
|
155
|
+
if (options.fallback === false) return this.#fail();
|
|
158
156
|
fallingBack = true;
|
|
159
157
|
return this.#fallBack(protocols);
|
|
160
158
|
} finally {
|
|
161
159
|
clearTimeout(timer);
|
|
162
160
|
}
|
|
163
|
-
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () =>
|
|
164
|
-
this.dispatchEvent(new Event("error"));
|
|
165
|
-
this.#end(1006, "", false);
|
|
166
|
-
});
|
|
161
|
+
transport.closed.then((info) => this.#end(info.closeCode || 1005, info.reason ?? "", true), () => this.#fail());
|
|
167
162
|
this.#state = OPEN;
|
|
168
163
|
this.dispatchEvent(new Event("open"));
|
|
169
164
|
}
|
|
@@ -228,6 +223,13 @@ function createWebTransportSocket(options = {}) {
|
|
|
228
223
|
if (data instanceof ArrayBuffer && this.binaryType === "blob") data = new Blob([data]);
|
|
229
224
|
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
230
225
|
}
|
|
226
|
+
/** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */
|
|
227
|
+
#fail() {
|
|
228
|
+
if (this.#state === CLOSED) return;
|
|
229
|
+
this.#transport?.close();
|
|
230
|
+
this.dispatchEvent(new Event("error"));
|
|
231
|
+
this.#end(1006, "", false);
|
|
232
|
+
}
|
|
231
233
|
#end(code, reason, wasClean) {
|
|
232
234
|
if (this.#state === CLOSED) return;
|
|
233
235
|
this.#state = CLOSED;
|
|
@@ -236,7 +238,6 @@ function createWebTransportSocket(options = {}) {
|
|
|
236
238
|
}
|
|
237
239
|
return WebTransportSocket;
|
|
238
240
|
}
|
|
239
|
-
//#endregion
|
|
240
241
|
export { createWebTransportSocket };
|
|
241
242
|
|
|
242
243
|
//# sourceMappingURL=webtransport.js.map
|
package/dist/webtransport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webtransport.js","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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 bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n void this.#connect(protocols);\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve()).then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n });\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) {\n this.dispatchEvent(new Event('error'));\n return this.#end(1006, '', false);\n }\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => {\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n }\n\n return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,QAAQ,KAAK,YAAY,KAAK,UAAU,CAAC;AAC/E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAAqC,CAAC,GACf;CACvB,MAAM,SAAS,QAAQ,SAAS,QAAgB,IA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,OAAO,MAAc,SAAqB;GACxC,KAAK,SAAS,SAAS,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM;EAClF;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,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"webtransport.js","names":[],"sources":["../src/webtransport.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Options for {@link createWebTransportSocket}. */\nexport interface WebTransportSocketOptions {\n /**\n * The WebTransport URL for the client's WebSocket URL.\n * @default `ws:` and `wss:` become `https:`\n */\n url?: (url: string) => string;\n /** Options for the `WebTransport` constructor, e.g. `serverCertificateHashes` in development. */\n transport?: WebTransportOptions;\n /**\n * The `WebSocket` to connect with where WebTransport isn't available, or when a session can't be\n * established, to the client's own URL. `false` fails the connection instead.\n * @default the global WebSocket\n */\n fallback?: typeof WebSocket | false;\n /**\n * How long to wait for a WebTransport session before falling back, in ms. UDP is blocked on\n * some networks, where the attempt only fails after a long time.\n * @default 5000\n */\n timeout?: number;\n /**\n * Send `volatile` messages as datagrams, which can be lost even while connected. `false` sends\n * every message on the stream.\n * @default true\n */\n datagrams?: boolean;\n}\n\n/** The class from {@link createWebTransportSocket}. */\nexport interface WebTransportWebSocket {\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 /** Whether connections go over WebSocket now, because WebTransport is missing or failed. */\n readonly fallingBack: boolean;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\nconst TEXT = 0;\nconst BINARY = 1;\n\n/** The method the client calls for `volatile` sends, where a socket has it. */\nconst DATAGRAM = Symbol.for('react-websocket.datagram');\n\ntype Data = Parameters<WebSocket['send']>[0];\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 bytes(data: Exclude<Data, Blob>): [number, Uint8Array] {\n if (typeof data === 'string') return [TEXT, new TextEncoder().encode(data)];\n if (data instanceof ArrayBuffer) return [BINARY, new Uint8Array(data)];\n return [BINARY, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)];\n}\n\n/**\n * Connect over [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API)\n * behind the same client API. Pass the returned class as the `WebSocket` option: messages go on\n * one reliable, ordered stream, and `volatile` sends go as datagrams, which are never queued or\n * retransmitted, so stale input or cursor positions don't hold up what comes after them.\n *\n * Where WebTransport isn't available, or a session can't be established within `timeout`, it\n * connects with a WebSocket to the client's own URL instead, and keeps doing so for later\n * connections.\n *\n * The server speaks a small framing over WebTransport: see the guide.\n *\n * @example\n * ```ts\n * import { createWebTransportSocket } from 'react-websocket/webtransport';\n *\n * export const game = createWebSocket('wss://game.example.com/play', {\n * json: true,\n * WebSocket: createWebTransportSocket()\n * });\n *\n * game.send({ type: 'aim', angle }, { volatile: true }); // a datagram\n * ```\n */\nexport function createWebTransportSocket(\n options: WebTransportSocketOptions = {}\n): WebTransportWebSocket {\n const mapUrl = options.url ?? ((url: string) => url.replace(/^ws(s?):/, 'https:'));\n const timeout = options.timeout ?? 5000;\n let fallingBack = false;\n\n class WebTransportSocket 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 #state: WebSocket['readyState'] = CONNECTING;\n #transport: WebTransport | undefined;\n #writer: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #datagrams: WritableStreamDefaultWriter<Uint8Array> | undefined;\n #inner: WebSocket | undefined;\n // Bytes handed to the stream and not yet written, like `bufferedAmount`.\n #buffered = 0;\n // Sends waiting for a Blob to be read, so they keep their order.\n #chain: Promise<void> | undefined;\n\n static get fallingBack() {\n return fallingBack || typeof WebTransport !== 'function';\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n if (typeof window === 'undefined') {\n throw new Error('react-websocket/webtransport: 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 (fallingBack || typeof WebTransport !== 'function') {\n this.#fallBack(protocols);\n return;\n }\n // A fallback that throws, e.g. for protocols the WebSocket rejects, fails the connection.\n this.#connect(protocols).catch(() => this.#fail());\n }\n\n get readyState() {\n return this.#state;\n }\n\n get bufferedAmount() {\n return this.#inner?.bufferedAmount ?? this.#buffered;\n }\n\n send(data: Data) {\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) return this.#inner.send(data);\n if (data instanceof Blob || this.#chain) {\n const chain = (this.#chain ?? Promise.resolve())\n .then(async () => {\n this.#write(...bytes(data instanceof Blob ? await data.arrayBuffer() : data));\n if (this.#chain === chain) this.#chain = undefined;\n })\n // A Blob that can't be read fails the connection, as in browsers, rather than\n // holding up every send after it.\n .catch(() => this.#fail());\n this.#chain = chain;\n return;\n }\n this.#write(...bytes(data));\n }\n\n /** A `volatile` send from the client: a datagram, unless it's too big for one. */\n [DATAGRAM](data: Data) {\n const transport = this.#transport;\n if (\n options.datagrams === false ||\n this.#inner ||\n !transport ||\n data instanceof Blob ||\n this.#state !== OPEN\n ) {\n return this.send(data);\n }\n const [type, payload] = bytes(data);\n if (payload.byteLength + 1 > transport.datagrams.maxDatagramSize) return this.send(data);\n const datagram = new Uint8Array(payload.byteLength + 1);\n datagram[0] = type;\n datagram.set(payload, 1);\n this.#datagrams!.write(datagram).catch(() => {});\n }\n\n close(code = 1000, reason = '') {\n if (this.#state >= CLOSING) return;\n const connecting = this.#state === CONNECTING;\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 if (!connecting) return this.#transport!.close({ closeCode: code, reason });\n // Not open yet: give up on the session, and report this close rather than its failure.\n this.#transport?.close();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n async #connect(protocols: string | string[] | undefined) {\n let transport: WebTransport;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n transport = this.#transport = new WebTransport(mapUrl(this.url), options.transport);\n // A session that fails rejects `closed` too, before anything listens to it.\n transport.closed.catch(() => {});\n await Promise.race([\n transport.ready,\n new Promise((_, reject) => (timer = setTimeout(reject, timeout, new Error('timeout'))))\n ]);\n const stream = await transport.createBidirectionalStream();\n if (this.#state !== CONNECTING) return transport.close();\n this.#writer = stream.writable.getWriter();\n this.#datagrams = transport.datagrams.writable.getWriter();\n void this.#read(stream.readable.getReader());\n void this.#readDatagrams(transport.datagrams.readable.getReader());\n } catch {\n // No session: fall back to a WebSocket for this connection and the ones after it.\n this.#transport?.close();\n this.#transport = undefined;\n // Closed while connecting: `close()` reports its own code.\n if (this.#state !== CONNECTING) return;\n if (options.fallback === false) return this.#fail();\n fallingBack = true;\n return this.#fallBack(protocols);\n } finally {\n clearTimeout(timer);\n }\n transport.closed.then(\n // A session ended without a code reports 0: like a WebSocket closed without a status.\n info => this.#end(info.closeCode || 1005, info.reason ?? '', true),\n () => this.#fail()\n );\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n }\n\n #fallBack(protocols: string | string[] | undefined) {\n const Impl =\n options.fallback === false ? undefined : (options.fallback ?? globalThis.WebSocket);\n if (!Impl) {\n throw new Error('react-websocket/webtransport: no WebTransport, and no fallback');\n }\n const inner = (this.#inner = new Impl(this.url, protocols));\n inner.binaryType = 'arraybuffer';\n inner.onopen = () => {\n this.protocol = inner.protocol;\n this.#state = OPEN;\n this.dispatchEvent(new Event('open'));\n };\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 }\n\n #write(type: number, payload: Uint8Array) {\n const frame = new Uint8Array(payload.byteLength + 5);\n const view = new DataView(frame.buffer);\n view.setUint8(0, type);\n view.setUint32(1, payload.byteLength);\n frame.set(payload, 5);\n this.#buffered += frame.byteLength;\n this.#writer!.write(frame).then(\n () => (this.#buffered -= frame.byteLength),\n () => {}\n );\n }\n\n /** Reassemble frames from the stream, whatever its chunks. */\n async #read(reader: ReadableStreamDefaultReader<Uint8Array>) {\n let buffer = new Uint8Array(0);\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n const joined = new Uint8Array(buffer.byteLength + value.byteLength);\n joined.set(buffer);\n joined.set(value, buffer.byteLength);\n buffer = joined;\n while (buffer.byteLength >= 5) {\n const view = new DataView(buffer.buffer, buffer.byteOffset);\n const length = view.getUint32(1);\n if (buffer.byteLength < 5 + length) break;\n this.#frame(view.getUint8(0), buffer.slice(5, 5 + length));\n buffer = buffer.slice(5 + length);\n }\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n async #readDatagrams(reader: ReadableStreamDefaultReader<Uint8Array>) {\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return;\n if (value.byteLength) this.#frame(value[0]!, value.slice(1));\n }\n } catch {\n // The session closed; `closed` reports it.\n }\n }\n\n #frame(type: number, payload: Uint8Array) {\n this.#message(type === TEXT ? new TextDecoder().decode(payload) : payload.buffer);\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 /** As a WebSocket that fails: `error`, then `close` with 1006. Ends a session still open. */\n #fail() {\n if (this.#state === CLOSED) return;\n this.#transport?.close();\n this.dispatchEvent(new Event('error'));\n this.#end(1006, '', false);\n }\n\n #end(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 return WebTransportSocket as unknown as WebTransportWebSocket;\n}\n"],"mappings":";AA2CA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,WAAW,OAAO,IAAI,0BAA0B;AAItD,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,MAAM,MAAiD;CAC9D,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CAC1E,IAAI,gBAAgB,aAAa,OAAO,CAAC,QAAQ,IAAI,WAAW,IAAI,CAAC;CACrE,OAAO,CAAC,QAAQ,IAAI,WAAW,KAAK,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C1C,IAAI,MAAM;KACV,IAAI,MAAM,YAAY,KAAK,OAAO,MAAM,IAAK,MAAM,MAAM,CAAC,CAAC;IAC7D;GACF,QAAQ,CAER;EACF;EAEA,OAAO,MAAc,SAAqB;GACxC,KAAK,SAAS,SAAS,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM;EAClF;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;;EAGA,QAAQ;GACN,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,YAAY,MAAM;GACvB,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;GACrC,KAAK,KAAK,MAAM,IAAI,KAAK;EAC3B;EAEA,KAAK,MAAc,QAAgB,UAAmB;GACpD,IAAI,KAAK,WAAW,QAAQ;GAC5B,KAAK,SAAS;GACd,KAAK,cAAc,WAAW,MAAM,QAAQ,QAAQ,CAAC;EACvD;CACF;CAEA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-websocket",
|
|
3
|
-
"version": "4.22.
|
|
3
|
+
"version": "4.22.3",
|
|
4
4
|
"description": "The real-time toolkit for React: a WebSocket hook with shared connections, auto-reconnect and typed messages, plus topics, state, requests, presence and AI agents",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -187,8 +187,8 @@
|
|
|
187
187
|
"react-dom": "^19.3.0",
|
|
188
188
|
"size-limit": "^14.2.0",
|
|
189
189
|
"typescript": "^7.0.2",
|
|
190
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@1.
|
|
191
|
-
"vite-plus": "1.
|
|
190
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
|
|
191
|
+
"vite-plus": "1.4.0",
|
|
192
192
|
"vitest": "5.0.5"
|
|
193
193
|
},
|
|
194
194
|
"size-limit": [
|
|
@@ -239,7 +239,7 @@
|
|
|
239
239
|
"ignore": [
|
|
240
240
|
"react"
|
|
241
241
|
],
|
|
242
|
-
"limit": "1.
|
|
242
|
+
"limit": "1.9 kB",
|
|
243
243
|
"gzip": true
|
|
244
244
|
},
|
|
245
245
|
{
|
|
@@ -249,7 +249,7 @@
|
|
|
249
249
|
"ignore": [
|
|
250
250
|
"react"
|
|
251
251
|
],
|
|
252
|
-
"limit": "1.
|
|
252
|
+
"limit": "1.8 kB",
|
|
253
253
|
"gzip": true
|
|
254
254
|
},
|
|
255
255
|
{
|
|
@@ -259,7 +259,7 @@
|
|
|
259
259
|
"ignore": [
|
|
260
260
|
"react"
|
|
261
261
|
],
|
|
262
|
-
"limit": "1.
|
|
262
|
+
"limit": "1.25 kB",
|
|
263
263
|
"gzip": true
|
|
264
264
|
},
|
|
265
265
|
{
|
|
@@ -279,7 +279,7 @@
|
|
|
279
279
|
"ignore": [
|
|
280
280
|
"react"
|
|
281
281
|
],
|
|
282
|
-
"limit": "
|
|
282
|
+
"limit": "780 B",
|
|
283
283
|
"gzip": true
|
|
284
284
|
},
|
|
285
285
|
{
|
|
@@ -296,7 +296,7 @@
|
|
|
296
296
|
"name": "react-websocket/chaos (createChaosWebSocket)",
|
|
297
297
|
"path": "dist/chaos.js",
|
|
298
298
|
"import": "{ createChaosWebSocket }",
|
|
299
|
-
"limit": "2.
|
|
299
|
+
"limit": "2.3 kB",
|
|
300
300
|
"gzip": true
|
|
301
301
|
},
|
|
302
302
|
{
|
|
@@ -353,7 +353,7 @@
|
|
|
353
353
|
}
|
|
354
354
|
],
|
|
355
355
|
"overrides": {
|
|
356
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@1.
|
|
356
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
|
|
357
357
|
"vitest": "5.0.5"
|
|
358
358
|
}
|
|
359
359
|
}
|