@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.
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,426 @@
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/channels.ts
21
+ var channels_exports = {};
22
+ __export(channels_exports, {
23
+ createChannelClient: () => createChannelClient
24
+ });
25
+ module.exports = __toCommonJS(channels_exports);
26
+ var import_reactive2 = require("@fluixi/reactive");
27
+
28
+ // src/serializers.ts
29
+ var raw = {
30
+ encode: (message) => message,
31
+ decode: (data) => data
32
+ };
33
+ function json() {
34
+ return {
35
+ encode: (message) => JSON.stringify(message),
36
+ decode: (data) => {
37
+ if (typeof data !== "string") throw new TypeError("json(): received a binary frame");
38
+ return JSON.parse(data);
39
+ }
40
+ };
41
+ }
42
+
43
+ // src/socket.ts
44
+ var import_reactive = require("@fluixi/reactive");
45
+
46
+ // src/transport.ts
47
+ function globalTransport() {
48
+ const Native = globalThis.WebSocket;
49
+ return Native ? (url, protocols) => new Native(url, protocols) : void 0;
50
+ }
51
+ function byteSize(data) {
52
+ if (typeof data === "string") {
53
+ return data.length < 1024 ? new TextEncoder().encode(data).length : utf8Length(data);
54
+ }
55
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
56
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
57
+ return data.byteLength ?? 0;
58
+ }
59
+ function utf8Length(text) {
60
+ let bytes = 0;
61
+ for (let i = 0; i < text.length; i++) {
62
+ const unit = text.charCodeAt(i);
63
+ if (unit < 128) bytes += 1;
64
+ else if (unit < 2048) bytes += 2;
65
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length) {
66
+ bytes += 4;
67
+ i++;
68
+ } else bytes += 3;
69
+ }
70
+ return bytes;
71
+ }
72
+
73
+ // src/socket.ts
74
+ var RealtimeError = class extends Error {
75
+ constructor(code, message, options) {
76
+ super(message);
77
+ this.name = "RealtimeError";
78
+ this.code = code;
79
+ if (options && "cause" in options) this.cause = options.cause;
80
+ }
81
+ };
82
+ var NO_RECONNECT_CODES = /* @__PURE__ */ new Set([1e3, 1008]);
83
+ var CLOSE_TOO_LARGE = 1009;
84
+ var CLOSE_HEARTBEAT = 4e3;
85
+ var CLOSE_TIMEOUT = 4001;
86
+ var BUFFER_POLL_MS = 100;
87
+ function createWebSocket(url, options = {}) {
88
+ const serializer = options.serializer ?? raw;
89
+ const policy = reconnectPolicy(options.reconnect);
90
+ const connectTimeout = options.connectTimeout ?? 1e4;
91
+ const queueLimit = options.queueLimit ?? 100;
92
+ const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
93
+ const keepLatest = options.keepLatest ?? true;
94
+ const transport = options.transport ?? (typeof document === "undefined" ? void 0 : globalTransport());
95
+ const status = (0, import_reactive.signal)("idle");
96
+ const data = (0, import_reactive.signal)(void 0, { equals: false });
97
+ const error = (0, import_reactive.signal)(void 0);
98
+ const info = (0, import_reactive.signal)({ url: void 0, protocol: "", attempt: 0, closeCode: void 0, closeReason: void 0 });
99
+ const buffered = (0, import_reactive.signal)(0);
100
+ const subscribers = /* @__PURE__ */ new Set();
101
+ const listeners = {
102
+ open: /* @__PURE__ */ new Set(),
103
+ close: /* @__PURE__ */ new Set(),
104
+ error: /* @__PURE__ */ new Set(),
105
+ discard: /* @__PURE__ */ new Set()
106
+ };
107
+ const queue = [];
108
+ let socket;
109
+ let generation = 0;
110
+ let failures = 0;
111
+ let disposed = false;
112
+ let autoConnect = options.connect !== false && !!transport;
113
+ let connectTimer;
114
+ let retryTimer;
115
+ let beatTimer;
116
+ let silenceTimer;
117
+ let bufferTimer;
118
+ const emit = (event, ...args) => {
119
+ for (const listener of [...listeners[event]]) call(listener, args);
120
+ };
121
+ const fail = (code, message, cause) => {
122
+ const failure = new RealtimeError(code, message, cause === void 0 ? void 0 : { cause });
123
+ error.set(failure);
124
+ emit("error", failure);
125
+ };
126
+ const patchInfo = (patch) => info.set((current) => ({ ...current, ...patch }));
127
+ const clearTimers = () => {
128
+ clearTimeout(connectTimer);
129
+ clearInterval(beatTimer);
130
+ clearTimeout(silenceTimer);
131
+ clearTimeout(bufferTimer);
132
+ connectTimer = beatTimer = silenceTimer = bufferTimer = void 0;
133
+ };
134
+ const watchSilence = () => {
135
+ if (!options.heartbeat) return;
136
+ clearTimeout(silenceTimer);
137
+ const timeout = options.heartbeat.timeout ?? options.heartbeat.interval * 2;
138
+ silenceTimer = setTimeout(() => {
139
+ fail("heartbeat-timeout", `No frame for ${timeout} ms`);
140
+ drop(CLOSE_HEARTBEAT, "heartbeat timeout");
141
+ }, timeout);
142
+ };
143
+ const trackBuffer = () => {
144
+ clearTimeout(bufferTimer);
145
+ const amount = socket?.bufferedAmount ?? 0;
146
+ buffered.set(amount);
147
+ if (amount > 0) bufferTimer = setTimeout(trackBuffer, BUFFER_POLL_MS);
148
+ };
149
+ const transmit = (frame) => {
150
+ socket.send(frame);
151
+ trackBuffer();
152
+ };
153
+ const discardQueue = () => {
154
+ if (!queue.length) return;
155
+ const lost2 = queue.splice(0).map((entry) => entry.message);
156
+ emit("discard", lost2);
157
+ };
158
+ const lost = (close) => {
159
+ clearTimers();
160
+ socket = void 0;
161
+ patchInfo({ closeCode: close.code, closeReason: close.reason });
162
+ const retry = policy && !disposed && policy.when(close);
163
+ if (retry && failures < policy.attempts) {
164
+ const delay = backoff(policy, failures);
165
+ failures += 1;
166
+ patchInfo({ attempt: failures });
167
+ status.set("reconnecting");
168
+ emit("close", close);
169
+ retryTimer = setTimeout(open, delay);
170
+ return;
171
+ }
172
+ status.set("closed");
173
+ if (retry) fail("reconnect-exhausted", `Gave up after ${failures} attempts`);
174
+ discardQueue();
175
+ emit("close", close);
176
+ };
177
+ const drop = (code, reason) => {
178
+ const current = socket;
179
+ generation += 1;
180
+ if (current) {
181
+ current.onopen = current.onmessage = current.onerror = current.onclose = null;
182
+ try {
183
+ current.close(code, reason);
184
+ } catch {
185
+ }
186
+ }
187
+ lost({ code, reason, wasClean: false });
188
+ };
189
+ const open = async () => {
190
+ retryTimer = void 0;
191
+ const attempt = ++generation;
192
+ status.set("connecting");
193
+ let address;
194
+ try {
195
+ address = typeof url === "function" ? await url() : url;
196
+ } catch (cause) {
197
+ if (attempt !== generation) return;
198
+ fail("connect-failed", "Could not get the connection address", cause);
199
+ return lost({ code: 1006, reason: "", wasClean: false });
200
+ }
201
+ if (attempt !== generation) return;
202
+ patchInfo({ url: address });
203
+ let next;
204
+ try {
205
+ next = transport(address, options.protocols);
206
+ } catch (cause) {
207
+ fail("connect-failed", `Could not open ${address}`, cause);
208
+ status.set("closed");
209
+ discardQueue();
210
+ return;
211
+ }
212
+ socket = next;
213
+ next.binaryType = options.binaryType ?? "arraybuffer";
214
+ connectTimer = setTimeout(() => {
215
+ fail("connect-timeout", `Not open after ${connectTimeout} ms`);
216
+ drop(CLOSE_TIMEOUT, "connect timeout");
217
+ }, connectTimeout);
218
+ next.onopen = () => {
219
+ if (attempt !== generation) return;
220
+ clearTimeout(connectTimer);
221
+ failures = 0;
222
+ (0, import_reactive.batch)(() => {
223
+ error.set(void 0);
224
+ patchInfo({ protocol: next.protocol, attempt: 0, closeCode: void 0, closeReason: void 0 });
225
+ status.set("open");
226
+ });
227
+ for (const entry of queue.splice(0)) transmit(entry.frame);
228
+ if (options.heartbeat) {
229
+ const { interval, message } = options.heartbeat;
230
+ if (message !== void 0) beatTimer = setInterval(() => socket && transmit(serializer.encode(message)), interval);
231
+ watchSilence();
232
+ }
233
+ emit("open");
234
+ };
235
+ next.onmessage = (event) => {
236
+ if (attempt !== generation) return;
237
+ watchSilence();
238
+ const frame = event.data;
239
+ if (byteSize(frame) > maxMessageSize) {
240
+ fail("message-too-large", `Received a message over ${maxMessageSize} bytes`);
241
+ return drop(CLOSE_TOO_LARGE, "message too large");
242
+ }
243
+ let message;
244
+ try {
245
+ message = serializer.decode(frame);
246
+ } catch (cause) {
247
+ return fail("decode-failed", "Could not decode a message", cause);
248
+ }
249
+ if (keepLatest) data.set(() => message);
250
+ for (const subscriber of [...subscribers]) call(subscriber, [message]);
251
+ };
252
+ next.onerror = () => attempt === generation && fail("connection-error", "The connection failed");
253
+ next.onclose = (close) => {
254
+ if (attempt !== generation) return;
255
+ lost({ code: close.code, reason: close.reason, wasClean: close.wasClean });
256
+ };
257
+ };
258
+ const connection = {
259
+ status,
260
+ connected: () => status() === "open",
261
+ data,
262
+ error,
263
+ info,
264
+ buffered,
265
+ connect() {
266
+ autoConnect = false;
267
+ if (disposed || !transport) return;
268
+ const now = (0, import_reactive.untrack)(status);
269
+ if (now === "open" || now === "connecting") return;
270
+ if (now === "closing") drop(1e3, "");
271
+ clearTimeout(retryTimer);
272
+ failures = 0;
273
+ void open();
274
+ },
275
+ send(message) {
276
+ const now = (0, import_reactive.untrack)(status);
277
+ if (disposed || now === "idle" && !autoConnect || now === "closing" || now === "closed") return "closed";
278
+ const frame = serializer.encode(message);
279
+ if (byteSize(frame) > maxMessageSize) return "too-large";
280
+ if (now === "open") {
281
+ transmit(frame);
282
+ return "sent";
283
+ }
284
+ if (queue.length >= queueLimit) return "queue-full";
285
+ queue.push({ message, frame });
286
+ return "queued";
287
+ },
288
+ subscribe(handler) {
289
+ subscribers.add(handler);
290
+ const stop = () => void subscribers.delete(handler);
291
+ if ((0, import_reactive.getOwner)()) (0, import_reactive.onCleanup)(stop);
292
+ return stop;
293
+ },
294
+ on(event, handler) {
295
+ const set = listeners[event];
296
+ set.add(handler);
297
+ const stop = () => void set.delete(handler);
298
+ if ((0, import_reactive.getOwner)()) (0, import_reactive.onCleanup)(stop);
299
+ return stop;
300
+ },
301
+ close(code = 1e3, reason = "") {
302
+ autoConnect = false;
303
+ clearTimeout(retryTimer);
304
+ retryTimer = void 0;
305
+ const current = socket;
306
+ generation += 1;
307
+ clearTimers();
308
+ if (!current) {
309
+ if ((0, import_reactive.untrack)(status) !== "idle") status.set("closed");
310
+ discardQueue();
311
+ return;
312
+ }
313
+ status.set("closing");
314
+ current.onopen = current.onmessage = current.onerror = null;
315
+ current.onclose = (close) => {
316
+ socket = void 0;
317
+ patchInfo({ closeCode: close.code, closeReason: close.reason });
318
+ status.set("closed");
319
+ emit("close", close);
320
+ };
321
+ discardQueue();
322
+ current.close(code, reason);
323
+ },
324
+ dispose() {
325
+ if (disposed) return;
326
+ connection.close();
327
+ disposed = true;
328
+ subscribers.clear();
329
+ for (const set of Object.values(listeners)) set.clear();
330
+ }
331
+ };
332
+ if ((0, import_reactive.getOwner)()) (0, import_reactive.onCleanup)(() => connection.dispose());
333
+ if (autoConnect) queueMicrotask(() => autoConnect && connection.connect());
334
+ return connection;
335
+ }
336
+ function reconnectPolicy(option) {
337
+ if (option === false) return void 0;
338
+ const given = option === true || option === void 0 ? {} : option;
339
+ return {
340
+ attempts: given.attempts ?? Infinity,
341
+ delay: given.delay ?? 500,
342
+ maxDelay: given.maxDelay ?? 3e4,
343
+ factor: given.factor ?? 2,
344
+ jitter: given.jitter ?? true,
345
+ when: given.when ?? ((close) => !NO_RECONNECT_CODES.has(close.code))
346
+ };
347
+ }
348
+ function backoff(policy, failures) {
349
+ const full = Math.min(policy.maxDelay, policy.delay * policy.factor ** failures);
350
+ return policy.jitter ? full / 2 + Math.random() * (full / 2) : full;
351
+ }
352
+ function call(handler, args) {
353
+ try {
354
+ handler(...args);
355
+ } catch (failure) {
356
+ queueMicrotask(() => {
357
+ throw failure;
358
+ });
359
+ }
360
+ }
361
+
362
+ // src/channels.ts
363
+ function createChannelClient(url, options = {}) {
364
+ const { silenceTimeout = 6e4, ...socketOptions } = options;
365
+ const connection = createWebSocket(url, {
366
+ ...socketOptions,
367
+ serializer: json(),
368
+ heartbeat: { interval: silenceTimeout / 2, timeout: silenceTimeout }
369
+ });
370
+ const channels = /* @__PURE__ */ new Map();
371
+ const join = (name, channel) => {
372
+ if (channel.joined || !(0, import_reactive2.untrack)(connection.connected)) return;
373
+ channel.joined = true;
374
+ connection.send(channel.last === void 0 ? { t: "join", c: name } : { t: "join", c: name, since: channel.last });
375
+ };
376
+ connection.on("open", () => {
377
+ for (const [name, channel] of channels) {
378
+ channel.joined = false;
379
+ join(name, channel);
380
+ }
381
+ });
382
+ connection.subscribe((frame) => {
383
+ if (frame.t === "ping" || frame.t === "joined") return;
384
+ const channel = channels.get(frame.c);
385
+ if (!channel) return;
386
+ const subscribers = [...channel.subscribers];
387
+ if (frame.t === "msg") {
388
+ channel.last = frame.m.id;
389
+ for (const subscriber of subscribers) subscriber.handler(frame.m);
390
+ } else if (frame.t === "resync") {
391
+ for (const subscriber of subscribers) subscriber.onResync?.();
392
+ } else if (frame.t === "denied") {
393
+ channels.delete(frame.c);
394
+ for (const subscriber of subscribers) subscriber.onDenied?.();
395
+ }
396
+ });
397
+ const client = {
398
+ status: connection.status,
399
+ connected: connection.connected,
400
+ error: connection.error,
401
+ connection,
402
+ subscribe(name, handler, handlers = {}) {
403
+ let channel = channels.get(name);
404
+ if (!channel) {
405
+ channel = { subscribers: /* @__PURE__ */ new Set(), last: void 0, joined: false };
406
+ channels.set(name, channel);
407
+ }
408
+ const subscriber = { handler, ...handlers };
409
+ channel.subscribers.add(subscriber);
410
+ join(name, channel);
411
+ const stop = () => {
412
+ const current = channels.get(name);
413
+ if (!current?.subscribers.delete(subscriber) || current.subscribers.size) return;
414
+ channels.delete(name);
415
+ if (current.joined && (0, import_reactive2.untrack)(connection.connected)) connection.send({ t: "leave", c: name });
416
+ };
417
+ if ((0, import_reactive2.getOwner)()) (0, import_reactive2.onCleanup)(stop);
418
+ return stop;
419
+ },
420
+ dispose() {
421
+ channels.clear();
422
+ connection.dispose();
423
+ }
424
+ };
425
+ return client;
426
+ }
@@ -0,0 +1,38 @@
1
+ import { type Accessor } from '@fluixi/reactive';
2
+ import type { ChannelMessage, ClientFrame, ServerFrame } from './channel-protocol.js';
3
+ import { type ConnectionStatus, type RealtimeError, type WebSocketConnection, type WebSocketOptions } from './socket.js';
4
+ export interface ChannelHandlers {
5
+ /**
6
+ * After a reconnect, the server could not send what was missed while away: refetch what the
7
+ * channel feeds.
8
+ */
9
+ onResync?: () => void;
10
+ /** The server refused the channel. */
11
+ onDenied?: () => void;
12
+ }
13
+ export interface ChannelClientOptions extends Omit<WebSocketOptions<ServerFrame, ClientFrame>, 'serializer' | 'heartbeat'> {
14
+ /**
15
+ * Silence that counts as a dead connection, in ms. The channel server sends a frame on every
16
+ * ping (25 s by default). Default: 60000
17
+ */
18
+ silenceTimeout?: number;
19
+ }
20
+ export interface ChannelClient {
21
+ status: Accessor<ConnectionStatus>;
22
+ connected: Accessor<boolean>;
23
+ error: Accessor<RealtimeError | undefined>;
24
+ /**
25
+ * Calls `handler` with every message on `channel`. The first subscriber joins it, the last to
26
+ * stop leaves it. Inside a reactive owner, stops with it.
27
+ */
28
+ subscribe<T = unknown>(channel: string, handler: (message: ChannelMessage<T>) => void, handlers?: ChannelHandlers): () => void;
29
+ /** The connection underneath. */
30
+ connection: WebSocketConnection<ServerFrame, ClientFrame>;
31
+ dispose(): void;
32
+ }
33
+ /**
34
+ * Channels from a channel server (`createChannelServer` in `@fluixi/realtime/server`) over one
35
+ * connection. After a reconnect each channel rejoins with the last id it saw.
36
+ */
37
+ export declare function createChannelClient(url: string | (() => string | Promise<string>), options?: ChannelClientOptions): ChannelClient;
38
+ //# sourceMappingURL=channels.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channels.d.ts","sourceRoot":"","sources":["../src/channels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE/E,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAAmB,KAAK,gBAAgB,EAAE,KAAK,aAAa,EAAE,KAAK,mBAAmB,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE1I,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,sCAAsC;IACtC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,gBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC,EAAE,YAAY,GAAG,WAAW,CAAC;IACxH;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IACnC,SAAS,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC7B,KAAK,EAAE,QAAQ,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;IAC3C;;;OAGG;IACH,SAAS,CAAC,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,EAAE,eAAe,GAAG,MAAM,IAAI,CAAC;IAC/H,iCAAiC;IACjC,UAAU,EAAE,mBAAmB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAC1D,OAAO,IAAI,IAAI,CAAC;CACjB;AAUD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,GAAE,oBAAyB,GAAG,aAAa,CAkErI"}
@@ -0,0 +1,82 @@
1
+ import { getOwner, onCleanup, untrack } from '@fluixi/reactive';
2
+ import { json } from './serializers.js';
3
+ import { createWebSocket } from './socket.js';
4
+ /**
5
+ * Channels from a channel server (`createChannelServer` in `@fluixi/realtime/server`) over one
6
+ * connection. After a reconnect each channel rejoins with the last id it saw.
7
+ */
8
+ export function createChannelClient(url, options = {}) {
9
+ const { silenceTimeout = 60_000, ...socketOptions } = options;
10
+ const connection = createWebSocket(url, {
11
+ ...socketOptions,
12
+ serializer: json(),
13
+ heartbeat: { interval: silenceTimeout / 2, timeout: silenceTimeout },
14
+ });
15
+ const channels = new Map();
16
+ const join = (name, channel) => {
17
+ if (channel.joined || !untrack(connection.connected))
18
+ return;
19
+ channel.joined = true;
20
+ connection.send(channel.last === undefined ? { t: 'join', c: name } : { t: 'join', c: name, since: channel.last });
21
+ };
22
+ connection.on('open', () => {
23
+ for (const [name, channel] of channels) {
24
+ channel.joined = false;
25
+ join(name, channel);
26
+ }
27
+ });
28
+ connection.subscribe((frame) => {
29
+ if (frame.t === 'ping' || frame.t === 'joined')
30
+ return;
31
+ const channel = channels.get(frame.c);
32
+ if (!channel)
33
+ return;
34
+ const subscribers = [...channel.subscribers];
35
+ if (frame.t === 'msg') {
36
+ channel.last = frame.m.id;
37
+ for (const subscriber of subscribers)
38
+ subscriber.handler(frame.m);
39
+ }
40
+ else if (frame.t === 'resync') {
41
+ for (const subscriber of subscribers)
42
+ subscriber.onResync?.();
43
+ }
44
+ else if (frame.t === 'denied') {
45
+ channels.delete(frame.c);
46
+ for (const subscriber of subscribers)
47
+ subscriber.onDenied?.();
48
+ }
49
+ });
50
+ const client = {
51
+ status: connection.status,
52
+ connected: connection.connected,
53
+ error: connection.error,
54
+ connection,
55
+ subscribe(name, handler, handlers = {}) {
56
+ let channel = channels.get(name);
57
+ if (!channel) {
58
+ channel = { subscribers: new Set(), last: undefined, joined: false };
59
+ channels.set(name, channel);
60
+ }
61
+ const subscriber = { handler: handler, ...handlers };
62
+ channel.subscribers.add(subscriber);
63
+ join(name, channel);
64
+ const stop = () => {
65
+ const current = channels.get(name);
66
+ if (!current?.subscribers.delete(subscriber) || current.subscribers.size)
67
+ return;
68
+ channels.delete(name);
69
+ if (current.joined && untrack(connection.connected))
70
+ connection.send({ t: 'leave', c: name });
71
+ };
72
+ if (getOwner())
73
+ onCleanup(stop);
74
+ return stop;
75
+ },
76
+ dispose() {
77
+ channels.clear();
78
+ connection.dispose();
79
+ },
80
+ };
81
+ return client;
82
+ }
@@ -0,0 +1,9 @@
1
+ import {
2
+ createChannelClient
3
+ } from "./chunk-MGON7IDW.mjs";
4
+ import "./chunk-UAZIXYV5.mjs";
5
+ import "./chunk-4CEAXWJN.mjs";
6
+ import "./chunk-X73D2DE2.mjs";
7
+ export {
8
+ createChannelClient
9
+ };
@@ -0,0 +1,31 @@
1
+ // src/transport.ts
2
+ function globalTransport() {
3
+ const Native = globalThis.WebSocket;
4
+ return Native ? (url, protocols) => new Native(url, protocols) : void 0;
5
+ }
6
+ function byteSize(data) {
7
+ if (typeof data === "string") {
8
+ return data.length < 1024 ? new TextEncoder().encode(data).length : utf8Length(data);
9
+ }
10
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
11
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
12
+ return data.byteLength ?? 0;
13
+ }
14
+ function utf8Length(text) {
15
+ let bytes = 0;
16
+ for (let i = 0; i < text.length; i++) {
17
+ const unit = text.charCodeAt(i);
18
+ if (unit < 128) bytes += 1;
19
+ else if (unit < 2048) bytes += 2;
20
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length) {
21
+ bytes += 4;
22
+ i++;
23
+ } else bytes += 3;
24
+ }
25
+ return bytes;
26
+ }
27
+
28
+ export {
29
+ globalTransport,
30
+ byteSize
31
+ };
@@ -0,0 +1,107 @@
1
+ import {
2
+ memoryBus
3
+ } from "./chunk-Q3NDGSX6.mjs";
4
+ import {
5
+ PING_FRAME,
6
+ parseClientFrame
7
+ } from "./chunk-DNVSSCJA.mjs";
8
+ import {
9
+ createWebSocketServer
10
+ } from "./chunk-GAAZQJJ4.mjs";
11
+
12
+ // src/channel-server.ts
13
+ function createChannelServer(options) {
14
+ const bus = options.bus ?? memoryBus();
15
+ const maxChannels = options.maxChannels ?? 100;
16
+ const members = /* @__PURE__ */ new Map();
17
+ const send = (connection, frame) => connection.send(JSON.stringify(frame));
18
+ const deliver = (channel, message) => {
19
+ for (const [connection, membership] of members.get(channel) ?? []) {
20
+ if (membership.held) membership.held.push(message);
21
+ else send(connection, { t: "msg", c: channel, m: message });
22
+ }
23
+ };
24
+ const unsubscribe = bus.subscribe(deliver);
25
+ const unwatchGaps = bus.onGap?.(() => {
26
+ for (const [channel, set] of members) for (const connection of set.keys()) send(connection, { t: "resync", c: channel });
27
+ });
28
+ const leave = (connection, channel) => {
29
+ const set = members.get(channel);
30
+ set?.delete(connection);
31
+ if (set && !set.size) members.delete(channel);
32
+ };
33
+ const join = async (connection, joined, channel, since) => {
34
+ if (joined.has(channel)) return;
35
+ if (joined.size >= maxChannels) return void send(connection, { t: "denied", c: channel });
36
+ joined.add(channel);
37
+ let allowed = false;
38
+ try {
39
+ allowed = await options.authorize(connection.context, channel);
40
+ } catch (error) {
41
+ console.error(error);
42
+ }
43
+ if (!joined.has(channel)) return;
44
+ if (!allowed) {
45
+ joined.delete(channel);
46
+ return void send(connection, { t: "denied", c: channel });
47
+ }
48
+ const membership = { held: since === void 0 ? null : [] };
49
+ if (!members.has(channel)) members.set(channel, /* @__PURE__ */ new Map());
50
+ members.get(channel).set(connection, membership);
51
+ send(connection, { t: "joined", c: channel });
52
+ if (since === void 0) return;
53
+ let missed = null;
54
+ try {
55
+ missed = options.replay ? await options.replay(channel, since, connection.context) : null;
56
+ } catch (error) {
57
+ console.error(error);
58
+ }
59
+ const held = membership.held ?? [];
60
+ membership.held = null;
61
+ if (!joined.has(channel)) return;
62
+ if (missed === null) {
63
+ send(connection, { t: "resync", c: channel });
64
+ return;
65
+ }
66
+ const replayed = new Set(missed.map((message) => message.id));
67
+ for (const message of missed) send(connection, { t: "msg", c: channel, m: message });
68
+ for (const message of held) if (!replayed.has(message.id)) send(connection, { t: "msg", c: channel, m: message });
69
+ };
70
+ const server = createWebSocketServer({
71
+ ...options,
72
+ keepAlive: PING_FRAME,
73
+ onConnection(connection) {
74
+ const joined = /* @__PURE__ */ new Set();
75
+ connection.on("message", (data) => {
76
+ const frame = typeof data === "string" ? parseClientFrame(data) : void 0;
77
+ if (!frame) return connection.close(1008, "unexpected frame");
78
+ if (frame.t === "join") void join(connection, joined, frame.c, frame.since);
79
+ else {
80
+ joined.delete(frame.c);
81
+ leave(connection, frame.c);
82
+ }
83
+ });
84
+ connection.on("close", () => {
85
+ for (const channel of joined) leave(connection, channel);
86
+ joined.clear();
87
+ });
88
+ }
89
+ });
90
+ return {
91
+ ...server,
92
+ async start() {
93
+ await bus.start?.();
94
+ },
95
+ publish: (channel, message) => bus.publish(channel, message),
96
+ async close(timeout) {
97
+ unsubscribe();
98
+ unwatchGaps?.();
99
+ await server.close(timeout);
100
+ await bus.close?.();
101
+ }
102
+ };
103
+ }
104
+
105
+ export {
106
+ createChannelServer
107
+ };