@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
@@ -0,0 +1,385 @@
1
+ /*! @fluixi/realtime v1.0.0-alpha.110 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/server.ts
22
+ var server_exports = {};
23
+ __export(server_exports, {
24
+ CLOSE_REAUTHENTICATE: () => CLOSE_REAUTHENTICATE,
25
+ createChannelServer: () => createChannelServer,
26
+ createWebSocketServer: () => createWebSocketServer,
27
+ memoryBus: () => memoryBus,
28
+ postgresBus: () => postgresBus
29
+ });
30
+ module.exports = __toCommonJS(server_exports);
31
+
32
+ // src/endpoint.ts
33
+ var import_ws = require("ws");
34
+ var DRAIN_POLL_MS = 20;
35
+ var CLOSE_REAUTHENTICATE = 4100;
36
+ var REFUSALS = {
37
+ 401: "Unauthorized",
38
+ 403: "Forbidden",
39
+ 503: "Service Unavailable"
40
+ };
41
+ function createWebSocketServer(options) {
42
+ const maxConnections = options.maxConnections ?? 1e4;
43
+ const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
44
+ const maxBuffered = options.maxBuffered ?? 4 * 1024 * 1024;
45
+ const pingInterval = options.pingInterval ?? 25e3;
46
+ const wss = new import_ws.WebSocketServer({ noServer: true, maxPayload: maxMessageSize });
47
+ const alive = /* @__PURE__ */ new WeakSet();
48
+ let pending = 0;
49
+ let closing = false;
50
+ const ping = setInterval(() => {
51
+ for (const ws of wss.clients) {
52
+ if (!alive.has(ws)) {
53
+ ws.terminate();
54
+ continue;
55
+ }
56
+ alive.delete(ws);
57
+ ws.ping();
58
+ if (options.keepAlive !== void 0) ws.send(options.keepAlive);
59
+ }
60
+ }, pingInterval);
61
+ ping.unref?.();
62
+ const allowedOrigin = (request) => {
63
+ const origin = request.headers.origin;
64
+ if (!origin) return true;
65
+ if (typeof options.origins === "function") return options.origins(origin, request);
66
+ if (options.origins) return options.origins.includes(origin);
67
+ try {
68
+ return new URL(origin).host === request.headers.host;
69
+ } catch {
70
+ return false;
71
+ }
72
+ };
73
+ const refuse = (socket, status) => {
74
+ if (socket.destroyed) return;
75
+ socket.end(`HTTP/1.1 ${status} ${REFUSALS[status]}\r
76
+ Connection: close\r
77
+ Content-Length: 0\r
78
+ \r
79
+ `);
80
+ };
81
+ const accept = async (request, socket, head) => {
82
+ if (closing || wss.clients.size + pending >= maxConnections) return refuse(socket, 503);
83
+ if (!allowedOrigin(request)) return refuse(socket, 403);
84
+ pending += 1;
85
+ let context;
86
+ try {
87
+ context = await options.authenticate(request);
88
+ } catch (error) {
89
+ console.error(error);
90
+ context = null;
91
+ } finally {
92
+ pending -= 1;
93
+ }
94
+ if (context === null) return refuse(socket, 401);
95
+ if (closing || socket.destroyed) return refuse(socket, 503);
96
+ wss.handleUpgrade(request, socket, head, (ws) => {
97
+ alive.add(ws);
98
+ ws.on("pong", () => alive.add(ws));
99
+ ws.on("error", () => {
100
+ });
101
+ if (options.maxAge) {
102
+ const timer = setTimeout(() => ws.close(CLOSE_REAUTHENTICATE, "reauthenticate"), options.maxAge);
103
+ timer.unref?.();
104
+ ws.once("close", () => clearTimeout(timer));
105
+ }
106
+ options.onConnection(wrap(ws, context, maxBuffered));
107
+ });
108
+ };
109
+ return {
110
+ upgrade(request, socket, head) {
111
+ const path = new URL(request.url ?? "/", "http://localhost").pathname;
112
+ if (path !== options.path) return false;
113
+ void accept(request, socket, head);
114
+ return true;
115
+ },
116
+ size: () => wss.clients.size,
117
+ close(timeout = 5e3) {
118
+ closing = true;
119
+ clearInterval(ping);
120
+ const open = [...wss.clients];
121
+ for (const ws of open) ws.close(1001, "server shutting down");
122
+ return new Promise((resolve) => {
123
+ const timer = setTimeout(() => {
124
+ for (const ws of wss.clients) ws.terminate();
125
+ }, timeout);
126
+ timer.unref?.();
127
+ const done = () => {
128
+ if (wss.clients.size) return;
129
+ clearTimeout(timer);
130
+ wss.close(() => resolve());
131
+ };
132
+ for (const ws of open) ws.once("close", done);
133
+ done();
134
+ });
135
+ }
136
+ };
137
+ }
138
+ function wrap(ws, context, maxBuffered) {
139
+ return {
140
+ context,
141
+ get buffered() {
142
+ return ws.bufferedAmount;
143
+ },
144
+ send(data) {
145
+ if (ws.readyState !== ws.OPEN) return "closed";
146
+ if (ws.bufferedAmount > maxBuffered) return "buffer-full";
147
+ ws.send(data);
148
+ return "sent";
149
+ },
150
+ drained(bytes = maxBuffered / 2) {
151
+ return new Promise((resolve) => {
152
+ const check = () => {
153
+ if (ws.readyState !== ws.OPEN || ws.bufferedAmount <= bytes) return resolve();
154
+ setTimeout(check, DRAIN_POLL_MS);
155
+ };
156
+ check();
157
+ });
158
+ },
159
+ close(code = 1e3, reason = "") {
160
+ ws.close(code, reason);
161
+ },
162
+ on(event, handler) {
163
+ const listener = event === "message" ? (data, isBinary) => {
164
+ const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
165
+ handler(isBinary ? new Uint8Array(bytes) : bytes.toString("utf8"));
166
+ } : (code, reason) => handler(code, reason.toString("utf8"));
167
+ ws.on(event, listener);
168
+ return () => void ws.off(event, listener);
169
+ }
170
+ };
171
+ }
172
+
173
+ // src/bus.ts
174
+ function memoryBus() {
175
+ const handlers = /* @__PURE__ */ new Set();
176
+ return {
177
+ async publish(channel, message) {
178
+ for (const handler of handlers) handler(channel, message);
179
+ },
180
+ subscribe(handler) {
181
+ handlers.add(handler);
182
+ return () => void handlers.delete(handler);
183
+ }
184
+ };
185
+ }
186
+ var MAX_PAYLOAD = 7999;
187
+ function postgresBus(options) {
188
+ const pgChannel = options.channel ?? "fluixi_realtime";
189
+ if (!/^[a-z_][a-z0-9_]*$/.test(pgChannel)) throw new Error(`postgresBus: "${pgChannel}" is not a plain lowercase identifier`);
190
+ const make = typeof options.listen === "function" ? options.listen : null;
191
+ let client = make ? make() : options.listen;
192
+ const notify = () => options.notify ?? client;
193
+ const handlers = /* @__PURE__ */ new Set();
194
+ const gaps = /* @__PURE__ */ new Set();
195
+ const firstDelay = options.reconnectDelay ?? 500;
196
+ let closed = false;
197
+ let retry;
198
+ const listener = (notification) => {
199
+ if (notification.channel !== pgChannel || !notification.payload) return;
200
+ let parsed;
201
+ try {
202
+ parsed = JSON.parse(notification.payload);
203
+ } catch {
204
+ return;
205
+ }
206
+ for (const handler of handlers) handler(parsed.c, parsed.m);
207
+ };
208
+ const attach = async (next) => {
209
+ let lost = false;
210
+ const onLost = () => {
211
+ if (lost || closed || !make) return;
212
+ lost = true;
213
+ next.off?.("notification", listener);
214
+ void next.end?.().catch(() => {
215
+ });
216
+ replace(firstDelay);
217
+ };
218
+ next.on("notification", listener);
219
+ next.on("error", onLost);
220
+ next.on("end", onLost);
221
+ try {
222
+ if (make) await next.connect?.();
223
+ await next.query(`LISTEN ${pgChannel}`);
224
+ } catch (error) {
225
+ lost = true;
226
+ next.off?.("notification", listener);
227
+ void next.end?.().catch(() => {
228
+ });
229
+ throw error;
230
+ }
231
+ };
232
+ const replace = (delay) => {
233
+ retry = setTimeout(async () => {
234
+ if (closed) return;
235
+ try {
236
+ client = make();
237
+ await attach(client);
238
+ for (const gap of [...gaps]) gap();
239
+ } catch {
240
+ replace(Math.min(delay * 2, 3e4));
241
+ }
242
+ }, delay);
243
+ retry.unref?.();
244
+ };
245
+ return {
246
+ async start() {
247
+ await attach(client);
248
+ },
249
+ async close() {
250
+ closed = true;
251
+ clearTimeout(retry);
252
+ client.off?.("notification", listener);
253
+ await client.query(`UNLISTEN ${pgChannel}`).catch(() => {
254
+ });
255
+ if (make) await client.end?.().catch(() => {
256
+ });
257
+ },
258
+ onGap(handler) {
259
+ gaps.add(handler);
260
+ return () => void gaps.delete(handler);
261
+ },
262
+ async publish(channel, message) {
263
+ const payload = JSON.stringify({ c: channel, m: message });
264
+ if (new TextEncoder().encode(payload).length > MAX_PAYLOAD) {
265
+ throw new Error(`postgresBus: a message on "${channel}" is over ${MAX_PAYLOAD} bytes; publish ids and let clients fetch`);
266
+ }
267
+ await notify().query("SELECT pg_notify($1, $2)", [pgChannel, payload]);
268
+ },
269
+ subscribe(handler) {
270
+ handlers.add(handler);
271
+ return () => void handlers.delete(handler);
272
+ }
273
+ };
274
+ }
275
+
276
+ // src/channel-protocol.ts
277
+ var PING_FRAME = '{"t":"ping"}';
278
+ function parseClientFrame(text) {
279
+ let frame;
280
+ try {
281
+ frame = JSON.parse(text);
282
+ } catch {
283
+ return void 0;
284
+ }
285
+ if (!frame || typeof frame !== "object") return void 0;
286
+ const { t, c, since } = frame;
287
+ if (typeof c !== "string" || !c || c.length > 200) return void 0;
288
+ if (t === "leave") return { t, c };
289
+ if (t !== "join") return void 0;
290
+ if (since === void 0) return { t, c };
291
+ return typeof since === "string" && since.length <= 200 ? { t, c, since } : void 0;
292
+ }
293
+
294
+ // src/channel-server.ts
295
+ function createChannelServer(options) {
296
+ const bus = options.bus ?? memoryBus();
297
+ const maxChannels = options.maxChannels ?? 100;
298
+ const members = /* @__PURE__ */ new Map();
299
+ const send = (connection, frame) => connection.send(JSON.stringify(frame));
300
+ const deliver = (channel, message) => {
301
+ for (const [connection, membership] of members.get(channel) ?? []) {
302
+ if (membership.held) membership.held.push(message);
303
+ else send(connection, { t: "msg", c: channel, m: message });
304
+ }
305
+ };
306
+ const unsubscribe = bus.subscribe(deliver);
307
+ const unwatchGaps = bus.onGap?.(() => {
308
+ for (const [channel, set] of members) for (const connection of set.keys()) send(connection, { t: "resync", c: channel });
309
+ });
310
+ const leave = (connection, channel) => {
311
+ const set = members.get(channel);
312
+ set?.delete(connection);
313
+ if (set && !set.size) members.delete(channel);
314
+ };
315
+ const join = async (connection, joined, channel, since) => {
316
+ if (joined.has(channel)) return;
317
+ if (joined.size >= maxChannels) return void send(connection, { t: "denied", c: channel });
318
+ joined.add(channel);
319
+ let allowed = false;
320
+ try {
321
+ allowed = await options.authorize(connection.context, channel);
322
+ } catch (error) {
323
+ console.error(error);
324
+ }
325
+ if (!joined.has(channel)) return;
326
+ if (!allowed) {
327
+ joined.delete(channel);
328
+ return void send(connection, { t: "denied", c: channel });
329
+ }
330
+ const membership = { held: since === void 0 ? null : [] };
331
+ if (!members.has(channel)) members.set(channel, /* @__PURE__ */ new Map());
332
+ members.get(channel).set(connection, membership);
333
+ send(connection, { t: "joined", c: channel });
334
+ if (since === void 0) return;
335
+ let missed = null;
336
+ try {
337
+ missed = options.replay ? await options.replay(channel, since, connection.context) : null;
338
+ } catch (error) {
339
+ console.error(error);
340
+ }
341
+ const held = membership.held ?? [];
342
+ membership.held = null;
343
+ if (!joined.has(channel)) return;
344
+ if (missed === null) {
345
+ send(connection, { t: "resync", c: channel });
346
+ return;
347
+ }
348
+ const replayed = new Set(missed.map((message) => message.id));
349
+ for (const message of missed) send(connection, { t: "msg", c: channel, m: message });
350
+ for (const message of held) if (!replayed.has(message.id)) send(connection, { t: "msg", c: channel, m: message });
351
+ };
352
+ const server = createWebSocketServer({
353
+ ...options,
354
+ keepAlive: PING_FRAME,
355
+ onConnection(connection) {
356
+ const joined = /* @__PURE__ */ new Set();
357
+ connection.on("message", (data) => {
358
+ const frame = typeof data === "string" ? parseClientFrame(data) : void 0;
359
+ if (!frame) return connection.close(1008, "unexpected frame");
360
+ if (frame.t === "join") void join(connection, joined, frame.c, frame.since);
361
+ else {
362
+ joined.delete(frame.c);
363
+ leave(connection, frame.c);
364
+ }
365
+ });
366
+ connection.on("close", () => {
367
+ for (const channel of joined) leave(connection, channel);
368
+ joined.clear();
369
+ });
370
+ }
371
+ });
372
+ return {
373
+ ...server,
374
+ async start() {
375
+ await bus.start?.();
376
+ },
377
+ publish: (channel, message) => bus.publish(channel, message),
378
+ async close(timeout) {
379
+ unsubscribe();
380
+ unwatchGaps?.();
381
+ await server.close(timeout);
382
+ await bus.close?.();
383
+ }
384
+ };
385
+ }
@@ -0,0 +1,5 @@
1
+ export { createWebSocketServer, CLOSE_REAUTHENTICATE, type RealtimeServer, type ServerConnection, type ServerSendData, type ServerSendResult, type WebSocketServerOptions, } from './endpoint.js';
2
+ export { createChannelServer, type ChannelServer, type ChannelServerOptions } from './channel-server.js';
3
+ export { memoryBus, postgresBus, type PostgresBusOptions, type PostgresNotifyClient, type RealtimeBus } from './bus.js';
4
+ export type { ChannelMessage } from './channel-protocol.js';
5
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,sBAAsB,GAC5B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,mBAAmB,EAAE,KAAK,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACzG,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AACxH,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/server.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createWebSocketServer, CLOSE_REAUTHENTICATE, } from './endpoint.js';
2
+ export { createChannelServer } from './channel-server.js';
3
+ export { memoryBus, postgresBus } from './bus.js';
@@ -0,0 +1,20 @@
1
+ /*! @fluixi/realtime v1.0.0-alpha.110 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
+ import {
3
+ createChannelServer
4
+ } from "./chunk-AWS4MP5D.mjs";
5
+ import {
6
+ memoryBus,
7
+ postgresBus
8
+ } from "./chunk-Q3NDGSX6.mjs";
9
+ import "./chunk-DNVSSCJA.mjs";
10
+ import {
11
+ CLOSE_REAUTHENTICATE,
12
+ createWebSocketServer
13
+ } from "./chunk-GAAZQJJ4.mjs";
14
+ export {
15
+ CLOSE_REAUTHENTICATE,
16
+ createChannelServer,
17
+ createWebSocketServer,
18
+ memoryBus,
19
+ postgresBus
20
+ };