@fluixi/realtime 0.0.0-stage → 1.0.0-alpha.109
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/LICENSE +21 -0
- package/README.md +24 -2
- package/dist/bus.cjs +127 -0
- package/dist/bus.d.ts +58 -0
- package/dist/bus.d.ts.map +1 -0
- package/dist/bus.js +118 -0
- package/dist/bus.mjs +8 -0
- package/dist/channel-protocol.cjs +42 -0
- package/dist/channel-protocol.d.ts +40 -0
- package/dist/channel-protocol.d.ts.map +1 -0
- package/dist/channel-protocol.js +24 -0
- package/dist/channel-protocol.mjs +8 -0
- package/dist/channel-server.cjs +291 -0
- package/dist/channel-server.d.ts +29 -0
- package/dist/channel-server.d.ts.map +1 -0
- package/dist/channel-server.js +122 -0
- package/dist/channel-server.mjs +9 -0
- package/dist/channels.cjs +426 -0
- package/dist/channels.d.ts +38 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/channels.js +82 -0
- package/dist/channels.mjs +9 -0
- package/dist/chunk-4CEAXWJN.mjs +31 -0
- package/dist/chunk-AWS4MP5D.mjs +107 -0
- package/dist/chunk-DNVSSCJA.mjs +22 -0
- package/dist/chunk-GAAZQJJ4.mjs +145 -0
- package/dist/chunk-MGON7IDW.mjs +77 -0
- package/dist/chunk-Q3NDGSX6.mjs +107 -0
- package/dist/chunk-UAZIXYV5.mjs +315 -0
- package/dist/chunk-X73D2DE2.mjs +19 -0
- package/dist/endpoint.cjs +165 -0
- package/dist/endpoint.d.ts +80 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +168 -0
- package/dist/endpoint.mjs +8 -0
- package/dist/index.cjs +445 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +29 -0
- package/dist/serializers.cjs +39 -0
- package/dist/serializers.d.ts +12 -0
- package/dist/serializers.d.ts.map +1 -0
- package/dist/serializers.js +16 -0
- package/dist/serializers.mjs +8 -0
- package/dist/server.cjs +385 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +3 -0
- package/dist/server.mjs +20 -0
- package/dist/socket.cjs +362 -0
- package/dist/socket.d.ts +137 -0
- package/dist/socket.d.ts.map +1 -0
- package/dist/socket.js +351 -0
- package/dist/socket.mjs +16 -0
- package/dist/transport.cjs +51 -0
- package/dist/transport.d.ts +33 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +36 -0
- package/dist/transport.mjs +8 -0
- package/dist/tsconfig.lib.tsbuildinfo +1 -0
- package/package.json +65 -3
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/channel-protocol.ts
|
|
2
|
+
var PING_FRAME = '{"t":"ping"}';
|
|
3
|
+
function parseClientFrame(text) {
|
|
4
|
+
let frame;
|
|
5
|
+
try {
|
|
6
|
+
frame = JSON.parse(text);
|
|
7
|
+
} catch {
|
|
8
|
+
return void 0;
|
|
9
|
+
}
|
|
10
|
+
if (!frame || typeof frame !== "object") return void 0;
|
|
11
|
+
const { t, c, since } = frame;
|
|
12
|
+
if (typeof c !== "string" || !c || c.length > 200) return void 0;
|
|
13
|
+
if (t === "leave") return { t, c };
|
|
14
|
+
if (t !== "join") return void 0;
|
|
15
|
+
if (since === void 0) return { t, c };
|
|
16
|
+
return typeof since === "string" && since.length <= 200 ? { t, c, since } : void 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
PING_FRAME,
|
|
21
|
+
parseClientFrame
|
|
22
|
+
};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// src/endpoint.ts
|
|
2
|
+
import { WebSocketServer } from "ws";
|
|
3
|
+
var DRAIN_POLL_MS = 20;
|
|
4
|
+
var CLOSE_REAUTHENTICATE = 4100;
|
|
5
|
+
var REFUSALS = {
|
|
6
|
+
401: "Unauthorized",
|
|
7
|
+
403: "Forbidden",
|
|
8
|
+
503: "Service Unavailable"
|
|
9
|
+
};
|
|
10
|
+
function createWebSocketServer(options) {
|
|
11
|
+
const maxConnections = options.maxConnections ?? 1e4;
|
|
12
|
+
const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
|
|
13
|
+
const maxBuffered = options.maxBuffered ?? 4 * 1024 * 1024;
|
|
14
|
+
const pingInterval = options.pingInterval ?? 25e3;
|
|
15
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: maxMessageSize });
|
|
16
|
+
const alive = /* @__PURE__ */ new WeakSet();
|
|
17
|
+
let pending = 0;
|
|
18
|
+
let closing = false;
|
|
19
|
+
const ping = setInterval(() => {
|
|
20
|
+
for (const ws of wss.clients) {
|
|
21
|
+
if (!alive.has(ws)) {
|
|
22
|
+
ws.terminate();
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
alive.delete(ws);
|
|
26
|
+
ws.ping();
|
|
27
|
+
if (options.keepAlive !== void 0) ws.send(options.keepAlive);
|
|
28
|
+
}
|
|
29
|
+
}, pingInterval);
|
|
30
|
+
ping.unref?.();
|
|
31
|
+
const allowedOrigin = (request) => {
|
|
32
|
+
const origin = request.headers.origin;
|
|
33
|
+
if (!origin) return true;
|
|
34
|
+
if (typeof options.origins === "function") return options.origins(origin, request);
|
|
35
|
+
if (options.origins) return options.origins.includes(origin);
|
|
36
|
+
try {
|
|
37
|
+
return new URL(origin).host === request.headers.host;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const refuse = (socket, status) => {
|
|
43
|
+
if (socket.destroyed) return;
|
|
44
|
+
socket.end(`HTTP/1.1 ${status} ${REFUSALS[status]}\r
|
|
45
|
+
Connection: close\r
|
|
46
|
+
Content-Length: 0\r
|
|
47
|
+
\r
|
|
48
|
+
`);
|
|
49
|
+
};
|
|
50
|
+
const accept = async (request, socket, head) => {
|
|
51
|
+
if (closing || wss.clients.size + pending >= maxConnections) return refuse(socket, 503);
|
|
52
|
+
if (!allowedOrigin(request)) return refuse(socket, 403);
|
|
53
|
+
pending += 1;
|
|
54
|
+
let context;
|
|
55
|
+
try {
|
|
56
|
+
context = await options.authenticate(request);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
console.error(error);
|
|
59
|
+
context = null;
|
|
60
|
+
} finally {
|
|
61
|
+
pending -= 1;
|
|
62
|
+
}
|
|
63
|
+
if (context === null) return refuse(socket, 401);
|
|
64
|
+
if (closing || socket.destroyed) return refuse(socket, 503);
|
|
65
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
66
|
+
alive.add(ws);
|
|
67
|
+
ws.on("pong", () => alive.add(ws));
|
|
68
|
+
ws.on("error", () => {
|
|
69
|
+
});
|
|
70
|
+
if (options.maxAge) {
|
|
71
|
+
const timer = setTimeout(() => ws.close(CLOSE_REAUTHENTICATE, "reauthenticate"), options.maxAge);
|
|
72
|
+
timer.unref?.();
|
|
73
|
+
ws.once("close", () => clearTimeout(timer));
|
|
74
|
+
}
|
|
75
|
+
options.onConnection(wrap(ws, context, maxBuffered));
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
upgrade(request, socket, head) {
|
|
80
|
+
const path = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
81
|
+
if (path !== options.path) return false;
|
|
82
|
+
void accept(request, socket, head);
|
|
83
|
+
return true;
|
|
84
|
+
},
|
|
85
|
+
size: () => wss.clients.size,
|
|
86
|
+
close(timeout = 5e3) {
|
|
87
|
+
closing = true;
|
|
88
|
+
clearInterval(ping);
|
|
89
|
+
const open = [...wss.clients];
|
|
90
|
+
for (const ws of open) ws.close(1001, "server shutting down");
|
|
91
|
+
return new Promise((resolve) => {
|
|
92
|
+
const timer = setTimeout(() => {
|
|
93
|
+
for (const ws of wss.clients) ws.terminate();
|
|
94
|
+
}, timeout);
|
|
95
|
+
timer.unref?.();
|
|
96
|
+
const done = () => {
|
|
97
|
+
if (wss.clients.size) return;
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
wss.close(() => resolve());
|
|
100
|
+
};
|
|
101
|
+
for (const ws of open) ws.once("close", done);
|
|
102
|
+
done();
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function wrap(ws, context, maxBuffered) {
|
|
108
|
+
return {
|
|
109
|
+
context,
|
|
110
|
+
get buffered() {
|
|
111
|
+
return ws.bufferedAmount;
|
|
112
|
+
},
|
|
113
|
+
send(data) {
|
|
114
|
+
if (ws.readyState !== ws.OPEN) return "closed";
|
|
115
|
+
if (ws.bufferedAmount > maxBuffered) return "buffer-full";
|
|
116
|
+
ws.send(data);
|
|
117
|
+
return "sent";
|
|
118
|
+
},
|
|
119
|
+
drained(bytes = maxBuffered / 2) {
|
|
120
|
+
return new Promise((resolve) => {
|
|
121
|
+
const check = () => {
|
|
122
|
+
if (ws.readyState !== ws.OPEN || ws.bufferedAmount <= bytes) return resolve();
|
|
123
|
+
setTimeout(check, DRAIN_POLL_MS);
|
|
124
|
+
};
|
|
125
|
+
check();
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
close(code = 1e3, reason = "") {
|
|
129
|
+
ws.close(code, reason);
|
|
130
|
+
},
|
|
131
|
+
on(event, handler) {
|
|
132
|
+
const listener = event === "message" ? (data, isBinary) => {
|
|
133
|
+
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
134
|
+
handler(isBinary ? new Uint8Array(bytes) : bytes.toString("utf8"));
|
|
135
|
+
} : (code, reason) => handler(code, reason.toString("utf8"));
|
|
136
|
+
ws.on(event, listener);
|
|
137
|
+
return () => void ws.off(event, listener);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export {
|
|
143
|
+
CLOSE_REAUTHENTICATE,
|
|
144
|
+
createWebSocketServer
|
|
145
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createWebSocket
|
|
3
|
+
} from "./chunk-UAZIXYV5.mjs";
|
|
4
|
+
import {
|
|
5
|
+
json
|
|
6
|
+
} from "./chunk-X73D2DE2.mjs";
|
|
7
|
+
|
|
8
|
+
// src/channels.ts
|
|
9
|
+
import { getOwner, onCleanup, untrack } from "@fluixi/reactive";
|
|
10
|
+
function createChannelClient(url, options = {}) {
|
|
11
|
+
const { silenceTimeout = 6e4, ...socketOptions } = options;
|
|
12
|
+
const connection = createWebSocket(url, {
|
|
13
|
+
...socketOptions,
|
|
14
|
+
serializer: json(),
|
|
15
|
+
heartbeat: { interval: silenceTimeout / 2, timeout: silenceTimeout }
|
|
16
|
+
});
|
|
17
|
+
const channels = /* @__PURE__ */ new Map();
|
|
18
|
+
const join = (name, channel) => {
|
|
19
|
+
if (channel.joined || !untrack(connection.connected)) return;
|
|
20
|
+
channel.joined = true;
|
|
21
|
+
connection.send(channel.last === void 0 ? { t: "join", c: name } : { t: "join", c: name, since: channel.last });
|
|
22
|
+
};
|
|
23
|
+
connection.on("open", () => {
|
|
24
|
+
for (const [name, channel] of channels) {
|
|
25
|
+
channel.joined = false;
|
|
26
|
+
join(name, channel);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
connection.subscribe((frame) => {
|
|
30
|
+
if (frame.t === "ping" || frame.t === "joined") return;
|
|
31
|
+
const channel = channels.get(frame.c);
|
|
32
|
+
if (!channel) return;
|
|
33
|
+
const subscribers = [...channel.subscribers];
|
|
34
|
+
if (frame.t === "msg") {
|
|
35
|
+
channel.last = frame.m.id;
|
|
36
|
+
for (const subscriber of subscribers) subscriber.handler(frame.m);
|
|
37
|
+
} else if (frame.t === "resync") {
|
|
38
|
+
for (const subscriber of subscribers) subscriber.onResync?.();
|
|
39
|
+
} else if (frame.t === "denied") {
|
|
40
|
+
channels.delete(frame.c);
|
|
41
|
+
for (const subscriber of subscribers) subscriber.onDenied?.();
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const client = {
|
|
45
|
+
status: connection.status,
|
|
46
|
+
connected: connection.connected,
|
|
47
|
+
error: connection.error,
|
|
48
|
+
connection,
|
|
49
|
+
subscribe(name, handler, handlers = {}) {
|
|
50
|
+
let channel = channels.get(name);
|
|
51
|
+
if (!channel) {
|
|
52
|
+
channel = { subscribers: /* @__PURE__ */ new Set(), last: void 0, joined: false };
|
|
53
|
+
channels.set(name, channel);
|
|
54
|
+
}
|
|
55
|
+
const subscriber = { handler, ...handlers };
|
|
56
|
+
channel.subscribers.add(subscriber);
|
|
57
|
+
join(name, channel);
|
|
58
|
+
const stop = () => {
|
|
59
|
+
const current = channels.get(name);
|
|
60
|
+
if (!current?.subscribers.delete(subscriber) || current.subscribers.size) return;
|
|
61
|
+
channels.delete(name);
|
|
62
|
+
if (current.joined && untrack(connection.connected)) connection.send({ t: "leave", c: name });
|
|
63
|
+
};
|
|
64
|
+
if (getOwner()) onCleanup(stop);
|
|
65
|
+
return stop;
|
|
66
|
+
},
|
|
67
|
+
dispose() {
|
|
68
|
+
channels.clear();
|
|
69
|
+
connection.dispose();
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
return client;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export {
|
|
76
|
+
createChannelClient
|
|
77
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// src/bus.ts
|
|
2
|
+
function memoryBus() {
|
|
3
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
4
|
+
return {
|
|
5
|
+
async publish(channel, message) {
|
|
6
|
+
for (const handler of handlers) handler(channel, message);
|
|
7
|
+
},
|
|
8
|
+
subscribe(handler) {
|
|
9
|
+
handlers.add(handler);
|
|
10
|
+
return () => void handlers.delete(handler);
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
var MAX_PAYLOAD = 7999;
|
|
15
|
+
function postgresBus(options) {
|
|
16
|
+
const pgChannel = options.channel ?? "fluixi_realtime";
|
|
17
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(pgChannel)) throw new Error(`postgresBus: "${pgChannel}" is not a plain lowercase identifier`);
|
|
18
|
+
const make = typeof options.listen === "function" ? options.listen : null;
|
|
19
|
+
let client = make ? make() : options.listen;
|
|
20
|
+
const notify = () => options.notify ?? client;
|
|
21
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
22
|
+
const gaps = /* @__PURE__ */ new Set();
|
|
23
|
+
const firstDelay = options.reconnectDelay ?? 500;
|
|
24
|
+
let closed = false;
|
|
25
|
+
let retry;
|
|
26
|
+
const listener = (notification) => {
|
|
27
|
+
if (notification.channel !== pgChannel || !notification.payload) return;
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(notification.payload);
|
|
31
|
+
} catch {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
for (const handler of handlers) handler(parsed.c, parsed.m);
|
|
35
|
+
};
|
|
36
|
+
const attach = async (next) => {
|
|
37
|
+
let lost = false;
|
|
38
|
+
const onLost = () => {
|
|
39
|
+
if (lost || closed || !make) return;
|
|
40
|
+
lost = true;
|
|
41
|
+
next.off?.("notification", listener);
|
|
42
|
+
void next.end?.().catch(() => {
|
|
43
|
+
});
|
|
44
|
+
replace(firstDelay);
|
|
45
|
+
};
|
|
46
|
+
next.on("notification", listener);
|
|
47
|
+
next.on("error", onLost);
|
|
48
|
+
next.on("end", onLost);
|
|
49
|
+
try {
|
|
50
|
+
if (make) await next.connect?.();
|
|
51
|
+
await next.query(`LISTEN ${pgChannel}`);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
lost = true;
|
|
54
|
+
next.off?.("notification", listener);
|
|
55
|
+
void next.end?.().catch(() => {
|
|
56
|
+
});
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const replace = (delay) => {
|
|
61
|
+
retry = setTimeout(async () => {
|
|
62
|
+
if (closed) return;
|
|
63
|
+
try {
|
|
64
|
+
client = make();
|
|
65
|
+
await attach(client);
|
|
66
|
+
for (const gap of [...gaps]) gap();
|
|
67
|
+
} catch {
|
|
68
|
+
replace(Math.min(delay * 2, 3e4));
|
|
69
|
+
}
|
|
70
|
+
}, delay);
|
|
71
|
+
retry.unref?.();
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
async start() {
|
|
75
|
+
await attach(client);
|
|
76
|
+
},
|
|
77
|
+
async close() {
|
|
78
|
+
closed = true;
|
|
79
|
+
clearTimeout(retry);
|
|
80
|
+
client.off?.("notification", listener);
|
|
81
|
+
await client.query(`UNLISTEN ${pgChannel}`).catch(() => {
|
|
82
|
+
});
|
|
83
|
+
if (make) await client.end?.().catch(() => {
|
|
84
|
+
});
|
|
85
|
+
},
|
|
86
|
+
onGap(handler) {
|
|
87
|
+
gaps.add(handler);
|
|
88
|
+
return () => void gaps.delete(handler);
|
|
89
|
+
},
|
|
90
|
+
async publish(channel, message) {
|
|
91
|
+
const payload = JSON.stringify({ c: channel, m: message });
|
|
92
|
+
if (new TextEncoder().encode(payload).length > MAX_PAYLOAD) {
|
|
93
|
+
throw new Error(`postgresBus: a message on "${channel}" is over ${MAX_PAYLOAD} bytes; publish ids and let clients fetch`);
|
|
94
|
+
}
|
|
95
|
+
await notify().query("SELECT pg_notify($1, $2)", [pgChannel, payload]);
|
|
96
|
+
},
|
|
97
|
+
subscribe(handler) {
|
|
98
|
+
handlers.add(handler);
|
|
99
|
+
return () => void handlers.delete(handler);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export {
|
|
105
|
+
memoryBus,
|
|
106
|
+
postgresBus
|
|
107
|
+
};
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import {
|
|
2
|
+
byteSize,
|
|
3
|
+
globalTransport
|
|
4
|
+
} from "./chunk-4CEAXWJN.mjs";
|
|
5
|
+
import {
|
|
6
|
+
raw
|
|
7
|
+
} from "./chunk-X73D2DE2.mjs";
|
|
8
|
+
|
|
9
|
+
// src/socket.ts
|
|
10
|
+
import { batch, getOwner, onCleanup, signal, untrack } from "@fluixi/reactive";
|
|
11
|
+
var CONNECTION_STATUSES = ["idle", "connecting", "open", "reconnecting", "closing", "closed"];
|
|
12
|
+
var REALTIME_ERROR_CODES = [
|
|
13
|
+
"connect-failed",
|
|
14
|
+
"connect-timeout",
|
|
15
|
+
"connection-error",
|
|
16
|
+
"heartbeat-timeout",
|
|
17
|
+
"message-too-large",
|
|
18
|
+
"decode-failed",
|
|
19
|
+
"reconnect-exhausted"
|
|
20
|
+
];
|
|
21
|
+
var RealtimeError = class extends Error {
|
|
22
|
+
constructor(code, message, options) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "RealtimeError";
|
|
25
|
+
this.code = code;
|
|
26
|
+
if (options && "cause" in options) this.cause = options.cause;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var NO_RECONNECT_CODES = /* @__PURE__ */ new Set([1e3, 1008]);
|
|
30
|
+
var CLOSE_TOO_LARGE = 1009;
|
|
31
|
+
var CLOSE_HEARTBEAT = 4e3;
|
|
32
|
+
var CLOSE_TIMEOUT = 4001;
|
|
33
|
+
var BUFFER_POLL_MS = 100;
|
|
34
|
+
function createWebSocket(url, options = {}) {
|
|
35
|
+
const serializer = options.serializer ?? raw;
|
|
36
|
+
const policy = reconnectPolicy(options.reconnect);
|
|
37
|
+
const connectTimeout = options.connectTimeout ?? 1e4;
|
|
38
|
+
const queueLimit = options.queueLimit ?? 100;
|
|
39
|
+
const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
|
|
40
|
+
const keepLatest = options.keepLatest ?? true;
|
|
41
|
+
const transport = options.transport ?? (typeof document === "undefined" ? void 0 : globalTransport());
|
|
42
|
+
const status = signal("idle");
|
|
43
|
+
const data = signal(void 0, { equals: false });
|
|
44
|
+
const error = signal(void 0);
|
|
45
|
+
const info = signal({ url: void 0, protocol: "", attempt: 0, closeCode: void 0, closeReason: void 0 });
|
|
46
|
+
const buffered = signal(0);
|
|
47
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
48
|
+
const listeners = {
|
|
49
|
+
open: /* @__PURE__ */ new Set(),
|
|
50
|
+
close: /* @__PURE__ */ new Set(),
|
|
51
|
+
error: /* @__PURE__ */ new Set(),
|
|
52
|
+
discard: /* @__PURE__ */ new Set()
|
|
53
|
+
};
|
|
54
|
+
const queue = [];
|
|
55
|
+
let socket;
|
|
56
|
+
let generation = 0;
|
|
57
|
+
let failures = 0;
|
|
58
|
+
let disposed = false;
|
|
59
|
+
let autoConnect = options.connect !== false && !!transport;
|
|
60
|
+
let connectTimer;
|
|
61
|
+
let retryTimer;
|
|
62
|
+
let beatTimer;
|
|
63
|
+
let silenceTimer;
|
|
64
|
+
let bufferTimer;
|
|
65
|
+
const emit = (event, ...args) => {
|
|
66
|
+
for (const listener of [...listeners[event]]) call(listener, args);
|
|
67
|
+
};
|
|
68
|
+
const fail = (code, message, cause) => {
|
|
69
|
+
const failure = new RealtimeError(code, message, cause === void 0 ? void 0 : { cause });
|
|
70
|
+
error.set(failure);
|
|
71
|
+
emit("error", failure);
|
|
72
|
+
};
|
|
73
|
+
const patchInfo = (patch) => info.set((current) => ({ ...current, ...patch }));
|
|
74
|
+
const clearTimers = () => {
|
|
75
|
+
clearTimeout(connectTimer);
|
|
76
|
+
clearInterval(beatTimer);
|
|
77
|
+
clearTimeout(silenceTimer);
|
|
78
|
+
clearTimeout(bufferTimer);
|
|
79
|
+
connectTimer = beatTimer = silenceTimer = bufferTimer = void 0;
|
|
80
|
+
};
|
|
81
|
+
const watchSilence = () => {
|
|
82
|
+
if (!options.heartbeat) return;
|
|
83
|
+
clearTimeout(silenceTimer);
|
|
84
|
+
const timeout = options.heartbeat.timeout ?? options.heartbeat.interval * 2;
|
|
85
|
+
silenceTimer = setTimeout(() => {
|
|
86
|
+
fail("heartbeat-timeout", `No frame for ${timeout} ms`);
|
|
87
|
+
drop(CLOSE_HEARTBEAT, "heartbeat timeout");
|
|
88
|
+
}, timeout);
|
|
89
|
+
};
|
|
90
|
+
const trackBuffer = () => {
|
|
91
|
+
clearTimeout(bufferTimer);
|
|
92
|
+
const amount = socket?.bufferedAmount ?? 0;
|
|
93
|
+
buffered.set(amount);
|
|
94
|
+
if (amount > 0) bufferTimer = setTimeout(trackBuffer, BUFFER_POLL_MS);
|
|
95
|
+
};
|
|
96
|
+
const transmit = (frame) => {
|
|
97
|
+
socket.send(frame);
|
|
98
|
+
trackBuffer();
|
|
99
|
+
};
|
|
100
|
+
const discardQueue = () => {
|
|
101
|
+
if (!queue.length) return;
|
|
102
|
+
const lost2 = queue.splice(0).map((entry) => entry.message);
|
|
103
|
+
emit("discard", lost2);
|
|
104
|
+
};
|
|
105
|
+
const lost = (close) => {
|
|
106
|
+
clearTimers();
|
|
107
|
+
socket = void 0;
|
|
108
|
+
patchInfo({ closeCode: close.code, closeReason: close.reason });
|
|
109
|
+
const retry = policy && !disposed && policy.when(close);
|
|
110
|
+
if (retry && failures < policy.attempts) {
|
|
111
|
+
const delay = backoff(policy, failures);
|
|
112
|
+
failures += 1;
|
|
113
|
+
patchInfo({ attempt: failures });
|
|
114
|
+
status.set("reconnecting");
|
|
115
|
+
emit("close", close);
|
|
116
|
+
retryTimer = setTimeout(open, delay);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
status.set("closed");
|
|
120
|
+
if (retry) fail("reconnect-exhausted", `Gave up after ${failures} attempts`);
|
|
121
|
+
discardQueue();
|
|
122
|
+
emit("close", close);
|
|
123
|
+
};
|
|
124
|
+
const drop = (code, reason) => {
|
|
125
|
+
const current = socket;
|
|
126
|
+
generation += 1;
|
|
127
|
+
if (current) {
|
|
128
|
+
current.onopen = current.onmessage = current.onerror = current.onclose = null;
|
|
129
|
+
try {
|
|
130
|
+
current.close(code, reason);
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
lost({ code, reason, wasClean: false });
|
|
135
|
+
};
|
|
136
|
+
const open = async () => {
|
|
137
|
+
retryTimer = void 0;
|
|
138
|
+
const attempt = ++generation;
|
|
139
|
+
status.set("connecting");
|
|
140
|
+
let address;
|
|
141
|
+
try {
|
|
142
|
+
address = typeof url === "function" ? await url() : url;
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
if (attempt !== generation) return;
|
|
145
|
+
fail("connect-failed", "Could not get the connection address", cause);
|
|
146
|
+
return lost({ code: 1006, reason: "", wasClean: false });
|
|
147
|
+
}
|
|
148
|
+
if (attempt !== generation) return;
|
|
149
|
+
patchInfo({ url: address });
|
|
150
|
+
let next;
|
|
151
|
+
try {
|
|
152
|
+
next = transport(address, options.protocols);
|
|
153
|
+
} catch (cause) {
|
|
154
|
+
fail("connect-failed", `Could not open ${address}`, cause);
|
|
155
|
+
status.set("closed");
|
|
156
|
+
discardQueue();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
socket = next;
|
|
160
|
+
next.binaryType = options.binaryType ?? "arraybuffer";
|
|
161
|
+
connectTimer = setTimeout(() => {
|
|
162
|
+
fail("connect-timeout", `Not open after ${connectTimeout} ms`);
|
|
163
|
+
drop(CLOSE_TIMEOUT, "connect timeout");
|
|
164
|
+
}, connectTimeout);
|
|
165
|
+
next.onopen = () => {
|
|
166
|
+
if (attempt !== generation) return;
|
|
167
|
+
clearTimeout(connectTimer);
|
|
168
|
+
failures = 0;
|
|
169
|
+
batch(() => {
|
|
170
|
+
error.set(void 0);
|
|
171
|
+
patchInfo({ protocol: next.protocol, attempt: 0, closeCode: void 0, closeReason: void 0 });
|
|
172
|
+
status.set("open");
|
|
173
|
+
});
|
|
174
|
+
for (const entry of queue.splice(0)) transmit(entry.frame);
|
|
175
|
+
if (options.heartbeat) {
|
|
176
|
+
const { interval, message } = options.heartbeat;
|
|
177
|
+
if (message !== void 0) beatTimer = setInterval(() => socket && transmit(serializer.encode(message)), interval);
|
|
178
|
+
watchSilence();
|
|
179
|
+
}
|
|
180
|
+
emit("open");
|
|
181
|
+
};
|
|
182
|
+
next.onmessage = (event) => {
|
|
183
|
+
if (attempt !== generation) return;
|
|
184
|
+
watchSilence();
|
|
185
|
+
const frame = event.data;
|
|
186
|
+
if (byteSize(frame) > maxMessageSize) {
|
|
187
|
+
fail("message-too-large", `Received a message over ${maxMessageSize} bytes`);
|
|
188
|
+
return drop(CLOSE_TOO_LARGE, "message too large");
|
|
189
|
+
}
|
|
190
|
+
let message;
|
|
191
|
+
try {
|
|
192
|
+
message = serializer.decode(frame);
|
|
193
|
+
} catch (cause) {
|
|
194
|
+
return fail("decode-failed", "Could not decode a message", cause);
|
|
195
|
+
}
|
|
196
|
+
if (keepLatest) data.set(() => message);
|
|
197
|
+
for (const subscriber of [...subscribers]) call(subscriber, [message]);
|
|
198
|
+
};
|
|
199
|
+
next.onerror = () => attempt === generation && fail("connection-error", "The connection failed");
|
|
200
|
+
next.onclose = (close) => {
|
|
201
|
+
if (attempt !== generation) return;
|
|
202
|
+
lost({ code: close.code, reason: close.reason, wasClean: close.wasClean });
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
const connection = {
|
|
206
|
+
status,
|
|
207
|
+
connected: () => status() === "open",
|
|
208
|
+
data,
|
|
209
|
+
error,
|
|
210
|
+
info,
|
|
211
|
+
buffered,
|
|
212
|
+
connect() {
|
|
213
|
+
autoConnect = false;
|
|
214
|
+
if (disposed || !transport) return;
|
|
215
|
+
const now = untrack(status);
|
|
216
|
+
if (now === "open" || now === "connecting") return;
|
|
217
|
+
if (now === "closing") drop(1e3, "");
|
|
218
|
+
clearTimeout(retryTimer);
|
|
219
|
+
failures = 0;
|
|
220
|
+
void open();
|
|
221
|
+
},
|
|
222
|
+
send(message) {
|
|
223
|
+
const now = untrack(status);
|
|
224
|
+
if (disposed || now === "idle" && !autoConnect || now === "closing" || now === "closed") return "closed";
|
|
225
|
+
const frame = serializer.encode(message);
|
|
226
|
+
if (byteSize(frame) > maxMessageSize) return "too-large";
|
|
227
|
+
if (now === "open") {
|
|
228
|
+
transmit(frame);
|
|
229
|
+
return "sent";
|
|
230
|
+
}
|
|
231
|
+
if (queue.length >= queueLimit) return "queue-full";
|
|
232
|
+
queue.push({ message, frame });
|
|
233
|
+
return "queued";
|
|
234
|
+
},
|
|
235
|
+
subscribe(handler) {
|
|
236
|
+
subscribers.add(handler);
|
|
237
|
+
const stop = () => void subscribers.delete(handler);
|
|
238
|
+
if (getOwner()) onCleanup(stop);
|
|
239
|
+
return stop;
|
|
240
|
+
},
|
|
241
|
+
on(event, handler) {
|
|
242
|
+
const set = listeners[event];
|
|
243
|
+
set.add(handler);
|
|
244
|
+
const stop = () => void set.delete(handler);
|
|
245
|
+
if (getOwner()) onCleanup(stop);
|
|
246
|
+
return stop;
|
|
247
|
+
},
|
|
248
|
+
close(code = 1e3, reason = "") {
|
|
249
|
+
autoConnect = false;
|
|
250
|
+
clearTimeout(retryTimer);
|
|
251
|
+
retryTimer = void 0;
|
|
252
|
+
const current = socket;
|
|
253
|
+
generation += 1;
|
|
254
|
+
clearTimers();
|
|
255
|
+
if (!current) {
|
|
256
|
+
if (untrack(status) !== "idle") status.set("closed");
|
|
257
|
+
discardQueue();
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
status.set("closing");
|
|
261
|
+
current.onopen = current.onmessage = current.onerror = null;
|
|
262
|
+
current.onclose = (close) => {
|
|
263
|
+
socket = void 0;
|
|
264
|
+
patchInfo({ closeCode: close.code, closeReason: close.reason });
|
|
265
|
+
status.set("closed");
|
|
266
|
+
emit("close", close);
|
|
267
|
+
};
|
|
268
|
+
discardQueue();
|
|
269
|
+
current.close(code, reason);
|
|
270
|
+
},
|
|
271
|
+
dispose() {
|
|
272
|
+
if (disposed) return;
|
|
273
|
+
connection.close();
|
|
274
|
+
disposed = true;
|
|
275
|
+
subscribers.clear();
|
|
276
|
+
for (const set of Object.values(listeners)) set.clear();
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
if (getOwner()) onCleanup(() => connection.dispose());
|
|
280
|
+
if (autoConnect) queueMicrotask(() => autoConnect && connection.connect());
|
|
281
|
+
return connection;
|
|
282
|
+
}
|
|
283
|
+
function reconnectPolicy(option) {
|
|
284
|
+
if (option === false) return void 0;
|
|
285
|
+
const given = option === true || option === void 0 ? {} : option;
|
|
286
|
+
return {
|
|
287
|
+
attempts: given.attempts ?? Infinity,
|
|
288
|
+
delay: given.delay ?? 500,
|
|
289
|
+
maxDelay: given.maxDelay ?? 3e4,
|
|
290
|
+
factor: given.factor ?? 2,
|
|
291
|
+
jitter: given.jitter ?? true,
|
|
292
|
+
when: given.when ?? ((close) => !NO_RECONNECT_CODES.has(close.code))
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function backoff(policy, failures) {
|
|
296
|
+
const full = Math.min(policy.maxDelay, policy.delay * policy.factor ** failures);
|
|
297
|
+
return policy.jitter ? full / 2 + Math.random() * (full / 2) : full;
|
|
298
|
+
}
|
|
299
|
+
function call(handler, args) {
|
|
300
|
+
try {
|
|
301
|
+
handler(...args);
|
|
302
|
+
} catch (failure) {
|
|
303
|
+
queueMicrotask(() => {
|
|
304
|
+
throw failure;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export {
|
|
310
|
+
CONNECTION_STATUSES,
|
|
311
|
+
REALTIME_ERROR_CODES,
|
|
312
|
+
RealtimeError,
|
|
313
|
+
createWebSocket,
|
|
314
|
+
backoff
|
|
315
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/serializers.ts
|
|
2
|
+
var raw = {
|
|
3
|
+
encode: (message) => message,
|
|
4
|
+
decode: (data) => data
|
|
5
|
+
};
|
|
6
|
+
function json() {
|
|
7
|
+
return {
|
|
8
|
+
encode: (message) => JSON.stringify(message),
|
|
9
|
+
decode: (data) => {
|
|
10
|
+
if (typeof data !== "string") throw new TypeError("json(): received a binary frame");
|
|
11
|
+
return JSON.parse(data);
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
raw,
|
|
18
|
+
json
|
|
19
|
+
};
|