@fluixi/realtime 0.0.0-stage → 1.0.0-alpha.110

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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/dist/bus.cjs +127 -0
  4. package/dist/bus.d.ts +58 -0
  5. package/dist/bus.d.ts.map +1 -0
  6. package/dist/bus.js +118 -0
  7. package/dist/bus.mjs +8 -0
  8. package/dist/channel-protocol.cjs +42 -0
  9. package/dist/channel-protocol.d.ts +40 -0
  10. package/dist/channel-protocol.d.ts.map +1 -0
  11. package/dist/channel-protocol.js +24 -0
  12. package/dist/channel-protocol.mjs +8 -0
  13. package/dist/channel-server.cjs +291 -0
  14. package/dist/channel-server.d.ts +29 -0
  15. package/dist/channel-server.d.ts.map +1 -0
  16. package/dist/channel-server.js +122 -0
  17. package/dist/channel-server.mjs +9 -0
  18. package/dist/channels.cjs +426 -0
  19. package/dist/channels.d.ts +38 -0
  20. package/dist/channels.d.ts.map +1 -0
  21. package/dist/channels.js +82 -0
  22. package/dist/channels.mjs +9 -0
  23. package/dist/chunk-4CEAXWJN.mjs +31 -0
  24. package/dist/chunk-AWS4MP5D.mjs +107 -0
  25. package/dist/chunk-DNVSSCJA.mjs +22 -0
  26. package/dist/chunk-GAAZQJJ4.mjs +145 -0
  27. package/dist/chunk-MGON7IDW.mjs +77 -0
  28. package/dist/chunk-Q3NDGSX6.mjs +107 -0
  29. package/dist/chunk-UAZIXYV5.mjs +315 -0
  30. package/dist/chunk-X73D2DE2.mjs +19 -0
  31. package/dist/endpoint.cjs +165 -0
  32. package/dist/endpoint.d.ts +80 -0
  33. package/dist/endpoint.d.ts.map +1 -0
  34. package/dist/endpoint.js +168 -0
  35. package/dist/endpoint.mjs +8 -0
  36. package/dist/index.cjs +445 -0
  37. package/dist/index.d.ts +6 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +4 -0
  40. package/dist/index.mjs +29 -0
  41. package/dist/serializers.cjs +39 -0
  42. package/dist/serializers.d.ts +12 -0
  43. package/dist/serializers.d.ts.map +1 -0
  44. package/dist/serializers.js +16 -0
  45. package/dist/serializers.mjs +8 -0
  46. package/dist/server.cjs +385 -0
  47. package/dist/server.d.ts +5 -0
  48. package/dist/server.d.ts.map +1 -0
  49. package/dist/server.js +3 -0
  50. package/dist/server.mjs +20 -0
  51. package/dist/socket.cjs +362 -0
  52. package/dist/socket.d.ts +137 -0
  53. package/dist/socket.d.ts.map +1 -0
  54. package/dist/socket.js +351 -0
  55. package/dist/socket.mjs +16 -0
  56. package/dist/transport.cjs +51 -0
  57. package/dist/transport.d.ts +33 -0
  58. package/dist/transport.d.ts.map +1 -0
  59. package/dist/transport.js +36 -0
  60. package/dist/transport.mjs +8 -0
  61. package/dist/tsconfig.lib.tsbuildinfo +1 -0
  62. package/package.json +65 -3
package/dist/socket.js ADDED
@@ -0,0 +1,351 @@
1
+ import { batch, getOwner, onCleanup, signal, untrack } from '@fluixi/reactive';
2
+ import { raw } from './serializers.js';
3
+ import { byteSize, globalTransport } from './transport.js';
4
+ export const CONNECTION_STATUSES = ['idle', 'connecting', 'open', 'reconnecting', 'closing', 'closed'];
5
+ export const REALTIME_ERROR_CODES = [
6
+ 'connect-failed',
7
+ 'connect-timeout',
8
+ 'connection-error',
9
+ 'heartbeat-timeout',
10
+ 'message-too-large',
11
+ 'decode-failed',
12
+ 'reconnect-exhausted',
13
+ ];
14
+ export class RealtimeError extends Error {
15
+ code;
16
+ /** What failed underneath, when something did. */
17
+ cause;
18
+ constructor(code, message, options) {
19
+ super(message);
20
+ this.name = 'RealtimeError';
21
+ this.code = code;
22
+ if (options && 'cause' in options)
23
+ this.cause = options.cause;
24
+ }
25
+ }
26
+ const NO_RECONNECT_CODES = new Set([1000, 1008]);
27
+ /** Closes the client starts. 4000 to 4999 are free for applications. */
28
+ const CLOSE_TOO_LARGE = 1009;
29
+ const CLOSE_HEARTBEAT = 4000;
30
+ const CLOSE_TIMEOUT = 4001;
31
+ const BUFFER_POLL_MS = 100;
32
+ export function createWebSocket(url, options = {}) {
33
+ const serializer = (options.serializer ?? raw);
34
+ const policy = reconnectPolicy(options.reconnect);
35
+ const connectTimeout = options.connectTimeout ?? 10_000;
36
+ const queueLimit = options.queueLimit ?? 100;
37
+ const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
38
+ const keepLatest = options.keepLatest ?? true;
39
+ // A server render has no document: `globalThis.WebSocket` exists in Node 22, and a module or
40
+ // component evaluated there must still open nothing.
41
+ const transport = options.transport ?? (typeof document === 'undefined' ? undefined : globalTransport());
42
+ const status = signal('idle');
43
+ const data = signal(undefined, { equals: false });
44
+ const error = signal(undefined);
45
+ const info = signal({ url: undefined, protocol: '', attempt: 0, closeCode: undefined, closeReason: undefined });
46
+ const buffered = signal(0);
47
+ const subscribers = new Set();
48
+ const listeners = {
49
+ open: new Set(),
50
+ close: new Set(),
51
+ error: new Set(),
52
+ discard: new Set(),
53
+ };
54
+ const queue = [];
55
+ let socket;
56
+ /** Bumped on every attempt and on close: callbacks from an older attempt find it changed. */
57
+ let generation = 0;
58
+ let failures = 0;
59
+ let disposed = false;
60
+ /** The automatic first connect, until it runs or something else decides. */
61
+ let autoConnect = options.connect !== false && !!transport;
62
+ let connectTimer;
63
+ let retryTimer;
64
+ let beatTimer;
65
+ let silenceTimer;
66
+ let bufferTimer;
67
+ const emit = (event, ...args) => {
68
+ for (const listener of [...listeners[event]])
69
+ call(listener, args);
70
+ };
71
+ const fail = (code, message, cause) => {
72
+ const failure = new RealtimeError(code, message, cause === undefined ? undefined : { cause });
73
+ error.set(failure);
74
+ emit('error', failure);
75
+ };
76
+ const patchInfo = (patch) => info.set((current) => ({ ...current, ...patch }));
77
+ const clearTimers = () => {
78
+ clearTimeout(connectTimer);
79
+ clearInterval(beatTimer);
80
+ clearTimeout(silenceTimer);
81
+ clearTimeout(bufferTimer);
82
+ connectTimer = beatTimer = silenceTimer = bufferTimer = undefined;
83
+ };
84
+ const watchSilence = () => {
85
+ if (!options.heartbeat)
86
+ return;
87
+ clearTimeout(silenceTimer);
88
+ const timeout = options.heartbeat.timeout ?? options.heartbeat.interval * 2;
89
+ silenceTimer = setTimeout(() => {
90
+ fail('heartbeat-timeout', `No frame for ${timeout} ms`);
91
+ drop(CLOSE_HEARTBEAT, 'heartbeat timeout');
92
+ }, timeout);
93
+ };
94
+ const trackBuffer = () => {
95
+ clearTimeout(bufferTimer);
96
+ const amount = socket?.bufferedAmount ?? 0;
97
+ buffered.set(amount);
98
+ if (amount > 0)
99
+ bufferTimer = setTimeout(trackBuffer, BUFFER_POLL_MS);
100
+ };
101
+ const transmit = (frame) => {
102
+ socket.send(frame);
103
+ trackBuffer();
104
+ };
105
+ const discardQueue = () => {
106
+ if (!queue.length)
107
+ return;
108
+ const lost = queue.splice(0).map((entry) => entry.message);
109
+ emit('discard', lost);
110
+ };
111
+ /** A socket that is gone: reconnect when the policy allows, else stop. */
112
+ const lost = (close) => {
113
+ clearTimers();
114
+ socket = undefined;
115
+ patchInfo({ closeCode: close.code, closeReason: close.reason });
116
+ const retry = policy && !disposed && policy.when(close);
117
+ if (retry && failures < policy.attempts) {
118
+ const delay = backoff(policy, failures);
119
+ failures += 1;
120
+ patchInfo({ attempt: failures });
121
+ status.set('reconnecting');
122
+ emit('close', close);
123
+ retryTimer = setTimeout(open, delay);
124
+ return;
125
+ }
126
+ status.set('closed');
127
+ if (retry)
128
+ fail('reconnect-exhausted', `Gave up after ${failures} attempts`);
129
+ discardQueue();
130
+ emit('close', close);
131
+ };
132
+ /** Lets go of the socket at once instead of waiting for a closing handshake that may never come. */
133
+ const drop = (code, reason) => {
134
+ const current = socket;
135
+ generation += 1;
136
+ if (current) {
137
+ current.onopen = current.onmessage = current.onerror = current.onclose = null;
138
+ try {
139
+ current.close(code, reason);
140
+ }
141
+ catch {
142
+ // Closing a socket that never opened can throw in some runtimes; it is gone either way.
143
+ }
144
+ }
145
+ lost({ code, reason, wasClean: false });
146
+ };
147
+ const open = async () => {
148
+ retryTimer = undefined;
149
+ const attempt = ++generation;
150
+ status.set('connecting');
151
+ let address;
152
+ try {
153
+ address = typeof url === 'function' ? await url() : url;
154
+ }
155
+ catch (cause) {
156
+ if (attempt !== generation)
157
+ return;
158
+ fail('connect-failed', 'Could not get the connection address', cause);
159
+ return lost({ code: 1006, reason: '', wasClean: false });
160
+ }
161
+ if (attempt !== generation)
162
+ return;
163
+ patchInfo({ url: address });
164
+ let next;
165
+ try {
166
+ next = transport(address, options.protocols);
167
+ }
168
+ catch (cause) {
169
+ // An address the transport refuses outright (bad scheme, malformed) will not get better.
170
+ fail('connect-failed', `Could not open ${address}`, cause);
171
+ status.set('closed');
172
+ discardQueue();
173
+ return;
174
+ }
175
+ socket = next;
176
+ next.binaryType = options.binaryType ?? 'arraybuffer';
177
+ connectTimer = setTimeout(() => {
178
+ fail('connect-timeout', `Not open after ${connectTimeout} ms`);
179
+ drop(CLOSE_TIMEOUT, 'connect timeout');
180
+ }, connectTimeout);
181
+ next.onopen = () => {
182
+ if (attempt !== generation)
183
+ return;
184
+ clearTimeout(connectTimer);
185
+ failures = 0;
186
+ batch(() => {
187
+ error.set(undefined);
188
+ patchInfo({ protocol: next.protocol, attempt: 0, closeCode: undefined, closeReason: undefined });
189
+ status.set('open');
190
+ });
191
+ for (const entry of queue.splice(0))
192
+ transmit(entry.frame);
193
+ if (options.heartbeat) {
194
+ const { interval, message } = options.heartbeat;
195
+ if (message !== undefined)
196
+ beatTimer = setInterval(() => socket && transmit(serializer.encode(message)), interval);
197
+ watchSilence();
198
+ }
199
+ emit('open');
200
+ };
201
+ next.onmessage = (event) => {
202
+ if (attempt !== generation)
203
+ return;
204
+ watchSilence();
205
+ const frame = event.data;
206
+ if (byteSize(frame) > maxMessageSize) {
207
+ fail('message-too-large', `Received a message over ${maxMessageSize} bytes`);
208
+ return drop(CLOSE_TOO_LARGE, 'message too large');
209
+ }
210
+ let message;
211
+ try {
212
+ message = serializer.decode(frame);
213
+ }
214
+ catch (cause) {
215
+ return fail('decode-failed', 'Could not decode a message', cause);
216
+ }
217
+ if (keepLatest)
218
+ data.set(() => message);
219
+ for (const subscriber of [...subscribers])
220
+ call(subscriber, [message]);
221
+ };
222
+ // The browser says nothing about why; the close event that follows carries the code.
223
+ next.onerror = () => attempt === generation && fail('connection-error', 'The connection failed');
224
+ next.onclose = (close) => {
225
+ if (attempt !== generation)
226
+ return;
227
+ lost({ code: close.code, reason: close.reason, wasClean: close.wasClean });
228
+ };
229
+ };
230
+ const connection = {
231
+ status,
232
+ connected: () => status() === 'open',
233
+ data,
234
+ error,
235
+ info,
236
+ buffered,
237
+ connect() {
238
+ autoConnect = false;
239
+ if (disposed || !transport)
240
+ return;
241
+ // Commands read the state without tracking it: called from an effect, they must not make
242
+ // it run again on every status change.
243
+ const now = untrack(status);
244
+ if (now === 'open' || now === 'connecting')
245
+ return;
246
+ if (now === 'closing')
247
+ drop(1000, '');
248
+ clearTimeout(retryTimer);
249
+ failures = 0;
250
+ void open();
251
+ },
252
+ send(message) {
253
+ const now = untrack(status);
254
+ if (disposed || (now === 'idle' && !autoConnect) || now === 'closing' || now === 'closed')
255
+ return 'closed';
256
+ const frame = serializer.encode(message);
257
+ if (byteSize(frame) > maxMessageSize)
258
+ return 'too-large';
259
+ if (now === 'open') {
260
+ transmit(frame);
261
+ return 'sent';
262
+ }
263
+ if (queue.length >= queueLimit)
264
+ return 'queue-full';
265
+ queue.push({ message, frame });
266
+ return 'queued';
267
+ },
268
+ subscribe(handler) {
269
+ subscribers.add(handler);
270
+ const stop = () => void subscribers.delete(handler);
271
+ if (getOwner())
272
+ onCleanup(stop);
273
+ return stop;
274
+ },
275
+ on(event, handler) {
276
+ const set = listeners[event];
277
+ set.add(handler);
278
+ const stop = () => void set.delete(handler);
279
+ if (getOwner())
280
+ onCleanup(stop);
281
+ return stop;
282
+ },
283
+ close(code = 1000, reason = '') {
284
+ autoConnect = false;
285
+ clearTimeout(retryTimer);
286
+ retryTimer = undefined;
287
+ const current = socket;
288
+ generation += 1;
289
+ clearTimers();
290
+ if (!current) {
291
+ if (untrack(status) !== 'idle')
292
+ status.set('closed');
293
+ discardQueue();
294
+ return;
295
+ }
296
+ status.set('closing');
297
+ current.onopen = current.onmessage = current.onerror = null;
298
+ current.onclose = (close) => {
299
+ socket = undefined;
300
+ patchInfo({ closeCode: close.code, closeReason: close.reason });
301
+ status.set('closed');
302
+ emit('close', close);
303
+ };
304
+ discardQueue();
305
+ current.close(code, reason);
306
+ },
307
+ dispose() {
308
+ if (disposed)
309
+ return;
310
+ connection.close();
311
+ disposed = true;
312
+ subscribers.clear();
313
+ for (const set of Object.values(listeners))
314
+ set.clear();
315
+ },
316
+ };
317
+ if (getOwner())
318
+ onCleanup(() => connection.dispose());
319
+ if (autoConnect)
320
+ queueMicrotask(() => autoConnect && connection.connect());
321
+ return connection;
322
+ }
323
+ function reconnectPolicy(option) {
324
+ if (option === false)
325
+ return undefined;
326
+ const given = option === true || option === undefined ? {} : option;
327
+ return {
328
+ attempts: given.attempts ?? Infinity,
329
+ delay: given.delay ?? 500,
330
+ maxDelay: given.maxDelay ?? 30_000,
331
+ factor: given.factor ?? 2,
332
+ jitter: given.jitter ?? true,
333
+ when: given.when ?? ((close) => !NO_RECONNECT_CODES.has(close.code)),
334
+ };
335
+ }
336
+ /** The wait before attempt `failures + 1`. */
337
+ export function backoff(policy, failures) {
338
+ const full = Math.min(policy.maxDelay, policy.delay * policy.factor ** failures);
339
+ return policy.jitter ? full / 2 + Math.random() * (full / 2) : full;
340
+ }
341
+ /** One handler failing must not stop the others: its error is reported on its own. */
342
+ function call(handler, args) {
343
+ try {
344
+ handler(...args);
345
+ }
346
+ catch (failure) {
347
+ queueMicrotask(() => {
348
+ throw failure;
349
+ });
350
+ }
351
+ }
@@ -0,0 +1,16 @@
1
+ import {
2
+ CONNECTION_STATUSES,
3
+ REALTIME_ERROR_CODES,
4
+ RealtimeError,
5
+ backoff,
6
+ createWebSocket
7
+ } from "./chunk-UAZIXYV5.mjs";
8
+ import "./chunk-4CEAXWJN.mjs";
9
+ import "./chunk-X73D2DE2.mjs";
10
+ export {
11
+ CONNECTION_STATUSES,
12
+ REALTIME_ERROR_CODES,
13
+ RealtimeError,
14
+ backoff,
15
+ createWebSocket
16
+ };
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/transport.ts
21
+ var transport_exports = {};
22
+ __export(transport_exports, {
23
+ byteSize: () => byteSize,
24
+ globalTransport: () => globalTransport
25
+ });
26
+ module.exports = __toCommonJS(transport_exports);
27
+ function globalTransport() {
28
+ const Native = globalThis.WebSocket;
29
+ return Native ? (url, protocols) => new Native(url, protocols) : void 0;
30
+ }
31
+ function byteSize(data) {
32
+ if (typeof data === "string") {
33
+ return data.length < 1024 ? new TextEncoder().encode(data).length : utf8Length(data);
34
+ }
35
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
36
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
37
+ return data.byteLength ?? 0;
38
+ }
39
+ function utf8Length(text) {
40
+ let bytes = 0;
41
+ for (let i = 0; i < text.length; i++) {
42
+ const unit = text.charCodeAt(i);
43
+ if (unit < 128) bytes += 1;
44
+ else if (unit < 2048) bytes += 2;
45
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length) {
46
+ bytes += 4;
47
+ i++;
48
+ } else bytes += 3;
49
+ }
50
+ return bytes;
51
+ }
@@ -0,0 +1,33 @@
1
+ /** What a WebSocket can carry: text, or bytes in any of the forms the browser accepts. */
2
+ export type SendData = string | ArrayBufferLike | ArrayBufferView | Blob;
3
+ /** What arrives: text frames as strings, binary frames as `ArrayBuffer` or `Blob` per `binaryType`. */
4
+ export type RawData = string | ArrayBuffer | Blob;
5
+ export interface CloseInfo {
6
+ code: number;
7
+ reason: string;
8
+ wasClean: boolean;
9
+ }
10
+ /**
11
+ * The part of the WebSocket interface the connection uses. The browser's `WebSocket` is one;
12
+ * a test double or another runtime's client can be another.
13
+ */
14
+ export interface WebSocketLike {
15
+ readonly protocol: string;
16
+ readonly bufferedAmount: number;
17
+ binaryType: 'arraybuffer' | 'blob';
18
+ send(data: SendData): void;
19
+ close(code?: number, reason?: string): void;
20
+ onopen: ((event: unknown) => void) | null;
21
+ onmessage: ((event: {
22
+ data: unknown;
23
+ }) => void) | null;
24
+ onerror: ((event: unknown) => void) | null;
25
+ onclose: ((event: CloseInfo) => void) | null;
26
+ }
27
+ /** Opens a socket. */
28
+ export type WebSocketTransport = (url: string, protocols?: string | string[]) => WebSocketLike;
29
+ /** The runtime's own `WebSocket`, when there is one. */
30
+ export declare function globalTransport(): WebSocketTransport | undefined;
31
+ /** Size in bytes of an outgoing or incoming message. */
32
+ export declare function byteSize(data: unknown): number;
33
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,eAAe,GAAG,eAAe,GAAG,IAAI,CAAC;AAEzE,uGAAuG;AACvG,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG,WAAW,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,UAAU,EAAE,aAAa,GAAG,MAAM,CAAC;IACnC,IAAI,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5C,MAAM,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IAC1C,SAAS,EAAE,CAAC,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACvD,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IAC3C,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9C;AAED,sBAAsB;AACtB,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,KAAK,aAAa,CAAC;AAE/F,wDAAwD;AACxD,wBAAgB,eAAe,IAAI,kBAAkB,GAAG,SAAS,CAKhE;AAED,wDAAwD;AACxD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAQ9C"}
@@ -0,0 +1,36 @@
1
+ /** The runtime's own `WebSocket`, when there is one. */
2
+ export function globalTransport() {
3
+ const Native = globalThis.WebSocket;
4
+ // The native handler properties take richer event types than WebSocketLike names, so the
5
+ // instance is compatible at runtime but not by declaration.
6
+ return Native ? (url, protocols) => new Native(url, protocols) : undefined;
7
+ }
8
+ /** Size in bytes of an outgoing or incoming message. */
9
+ export function byteSize(data) {
10
+ if (typeof data === 'string') {
11
+ // Each UTF-16 unit is at most 3 bytes in UTF-8: count exactly only when the bound is close.
12
+ return data.length < 1024 ? new TextEncoder().encode(data).length : utf8Length(data);
13
+ }
14
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data))
15
+ return data.byteLength;
16
+ if (typeof Blob !== 'undefined' && data instanceof Blob)
17
+ return data.size;
18
+ return data.byteLength ?? 0;
19
+ }
20
+ function utf8Length(text) {
21
+ let bytes = 0;
22
+ for (let i = 0; i < text.length; i++) {
23
+ const unit = text.charCodeAt(i);
24
+ if (unit < 0x80)
25
+ bytes += 1;
26
+ else if (unit < 0x800)
27
+ bytes += 2;
28
+ else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length) {
29
+ bytes += 4;
30
+ i++;
31
+ }
32
+ else
33
+ bytes += 3;
34
+ }
35
+ return bytes;
36
+ }
@@ -0,0 +1,8 @@
1
+ import {
2
+ byteSize,
3
+ globalTransport
4
+ } from "./chunk-4CEAXWJN.mjs";
5
+ export {
6
+ byteSize,
7
+ globalTransport
8
+ };