@mjczone/realtime-client 0.0.0-stage → 0.0.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MJCZone, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,72 @@
1
+ /** Throw this from a token callback on 401 or 403, so the client stops retrying. */
2
+ export { UnauthorizedError } from 'centrifuge';
3
+ import { type Envelope } from '@mjczone/realtime-contract';
4
+ export type ConnectionState = 'disconnected' | 'connecting' | 'connected';
5
+ export interface StreamPosition {
6
+ offset: number;
7
+ epoch: string;
8
+ }
9
+ export interface ClientOptions {
10
+ /** Backbone client endpoint, for example https://rt.example.com */
11
+ url: string;
12
+ getConnectionToken: () => Promise<string>;
13
+ getSubscriptionToken: (channel: string) => Promise<string>;
14
+ /** Transports to try, in order. Default: websocket, then http_stream, then sse. */
15
+ transports?: Array<'websocket' | 'http_stream' | 'sse'>;
16
+ /** Passed to centrifuge-js, for example a WebSocket implementation outside the browser. */
17
+ websocket?: unknown;
18
+ debug?: boolean;
19
+ }
20
+ export interface MessageContext {
21
+ channel: string;
22
+ /** Position of this message in the stream, for channels with history. */
23
+ offset?: number;
24
+ }
25
+ export interface SubscribedInfo {
26
+ /** True when this subscribe tried to recover from a position. */
27
+ wasRecovering: boolean;
28
+ /** True when every missed message was recovered. False after wasRecovering means history was lost. */
29
+ recovered: boolean;
30
+ position?: StreamPosition;
31
+ }
32
+ export interface PresenceMember {
33
+ clientId: string;
34
+ userId: string;
35
+ info?: unknown;
36
+ }
37
+ export interface SubscribeOptions {
38
+ /** Start from this stream position. Messages strictly after `offset` are delivered. */
39
+ since?: StreamPosition;
40
+ /** A subscription token already in hand, such as the one a run endpoint returns. Refreshes still use getSubscriptionToken. */
41
+ token?: string;
42
+ /** How many recent message IDs to remember for dedupe. Default 1000. */
43
+ dedupeSize?: number;
44
+ onSubscribed?: (info: SubscribedInfo) => void;
45
+ /** A transient error. The client keeps retrying. */
46
+ onError?: (error: {
47
+ code: number;
48
+ message: string;
49
+ }) => void;
50
+ /** The subscription ended and will not retry, for example 103 permission denied or an UnauthorizedError from the token callback. */
51
+ onFailed?: (error: {
52
+ code: number;
53
+ message: string;
54
+ }) => void;
55
+ onJoin?: (member: PresenceMember) => void;
56
+ onLeave?: (member: PresenceMember) => void;
57
+ }
58
+ export interface RealtimeSubscription {
59
+ readonly channel: string;
60
+ /** The last seen stream position, for reattaching later. */
61
+ readonly position: StreamPosition | undefined;
62
+ roster(): Promise<PresenceMember[]>;
63
+ unsubscribe(): void;
64
+ }
65
+ export interface RealtimeClient {
66
+ readonly state: ConnectionState;
67
+ onStateChange(cb: (state: ConnectionState) => void): () => void;
68
+ connect(): void;
69
+ disconnect(): void;
70
+ subscribe<T extends object = Record<string, unknown>>(channel: string, handler: (envelope: Envelope<T>, ctx: MessageContext) => void, options?: SubscribeOptions): RealtimeSubscription;
71
+ }
72
+ export declare function createRealtimeClient(options: ClientOptions): RealtimeClient;
package/dist/client.js ADDED
@@ -0,0 +1,122 @@
1
+ import { Centrifuge } from 'centrifuge';
2
+ /** Throw this from a token callback on 401 or 403, so the client stops retrying. */
3
+ export { UnauthorizedError } from 'centrifuge';
4
+ import { tryParseChannel, validateEnvelope } from '@mjczone/realtime-contract';
5
+ class RecentIds {
6
+ max;
7
+ ids = new Set();
8
+ constructor(max) {
9
+ this.max = max;
10
+ }
11
+ /** Returns false when the ID was already seen. */
12
+ add(id) {
13
+ if (this.ids.has(id))
14
+ return false;
15
+ this.ids.add(id);
16
+ if (this.ids.size > this.max)
17
+ this.ids.delete(this.ids.values().next().value);
18
+ return true;
19
+ }
20
+ }
21
+ function endpoints(url, names) {
22
+ const base = url.replace(/\/$/, '');
23
+ const ws = base.replace(/^http/, 'ws');
24
+ return names.map((transport) => ({
25
+ transport,
26
+ endpoint: transport === 'websocket' ? `${ws}/connection/websocket` : `${base}/connection/${transport}`,
27
+ }));
28
+ }
29
+ function member(info) {
30
+ return { clientId: info.client, userId: info.user, info: info.connInfo };
31
+ }
32
+ export function createRealtimeClient(options) {
33
+ const base = options.url.replace(/\/$/, '');
34
+ const centrifuge = new Centrifuge(endpoints(base, options.transports ?? ['websocket', 'http_stream', 'sse']), {
35
+ getToken: options.getConnectionToken,
36
+ emulationEndpoint: `${base}/emulation`,
37
+ debug: options.debug ?? false,
38
+ ...(options.websocket ? { websocket: options.websocket } : {}),
39
+ });
40
+ const listeners = new Set();
41
+ let state = 'disconnected';
42
+ const setState = (s) => {
43
+ state = s;
44
+ listeners.forEach((cb) => cb(s));
45
+ };
46
+ centrifuge.on('connecting', () => setState('connecting'));
47
+ centrifuge.on('connected', () => setState('connected'));
48
+ centrifuge.on('disconnected', () => setState('disconnected'));
49
+ return {
50
+ get state() {
51
+ return state;
52
+ },
53
+ onStateChange(cb) {
54
+ listeners.add(cb);
55
+ return () => listeners.delete(cb);
56
+ },
57
+ connect: () => centrifuge.connect(),
58
+ disconnect: () => centrifuge.disconnect(),
59
+ subscribe(channel, handler, opts = {}) {
60
+ const parsed = tryParseChannel(channel);
61
+ if (!parsed)
62
+ throw new Error(`Invalid channel name: ${channel}`);
63
+ const old = centrifuge.getSubscription(channel);
64
+ if (old)
65
+ centrifuge.removeSubscription(old);
66
+ const seen = new RecentIds(opts.dedupeSize ?? 1000);
67
+ let position = opts.since ? { ...opts.since } : undefined;
68
+ const sub = centrifuge.newSubscription(channel, {
69
+ getToken: parsed.userId === undefined ? () => options.getSubscriptionToken(channel) : null,
70
+ since: opts.since ?? null,
71
+ ...(opts.token ? { token: opts.token } : {}),
72
+ });
73
+ sub.on('subscribed', (ctx) => {
74
+ if (ctx.streamPosition)
75
+ position = { offset: ctx.streamPosition.offset, epoch: ctx.streamPosition.epoch };
76
+ opts.onSubscribed?.({
77
+ wasRecovering: ctx.wasRecovering,
78
+ recovered: ctx.recovered,
79
+ position: position && { ...position },
80
+ });
81
+ });
82
+ sub.on('publication', (ctx) => {
83
+ if (ctx.offset !== undefined && position)
84
+ position = { offset: ctx.offset, epoch: position.epoch };
85
+ const problem = validateEnvelope(ctx.data);
86
+ if (problem) {
87
+ console.warn(`realtime: dropped invalid envelope on ${channel}: ${problem}`);
88
+ return;
89
+ }
90
+ const env = ctx.data;
91
+ if (!seen.add(env.id))
92
+ return;
93
+ handler(env, { channel, offset: ctx.offset });
94
+ });
95
+ sub.on('error', (ctx) => opts.onError?.(ctx.error));
96
+ sub.on('unsubscribed', (ctx) => {
97
+ if (ctx.code !== 0)
98
+ opts.onFailed?.({ code: ctx.code, message: ctx.reason });
99
+ });
100
+ if (opts.onJoin)
101
+ sub.on('join', (ctx) => opts.onJoin(member(ctx.info)));
102
+ if (opts.onLeave)
103
+ sub.on('leave', (ctx) => opts.onLeave(member(ctx.info)));
104
+ sub.subscribe();
105
+ return {
106
+ channel,
107
+ get position() {
108
+ return position && { ...position };
109
+ },
110
+ async roster() {
111
+ const r = await sub.presence();
112
+ return Object.values(r.clients).map(member);
113
+ },
114
+ unsubscribe() {
115
+ sub.unsubscribe();
116
+ centrifuge.removeSubscription(sub);
117
+ },
118
+ };
119
+ },
120
+ };
121
+ }
122
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAA+D,MAAM,YAAY,CAAC;AAErG,oFAAoF;AACpF,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAiB,MAAM,4BAA4B,CAAC;AA6E9F,MAAM,SAAS;IAEgB,GAAG;IADf,GAAG,GAAG,IAAI,GAAG,EAAU,CAAC;IACzC,YAA6B,GAAW;mBAAX,GAAG;IAAW,CAAC;IAE5C,kDAAkD;IAClD,GAAG,CAAC,EAAU;QACZ,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAAE,OAAO,KAAK,CAAC;QACnC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACjB,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAe,CAAC,CAAC;QACxF,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED,SAAS,SAAS,CAAC,GAAW,EAAE,KAAiD;IAC/E,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,C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AC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBAC9C,CAAC;gBACD,WAAW;oBACT,GAAG,CAAC,WAAW,EAAE,CAAC;oBAClB,UAAU,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC;gBACrC,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1 @@
1
+ export * from './client.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './client.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@mjczone/realtime-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Browser client for the realtime backbone: centrifuge-js with envelopes, dedupe and presence",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mjczone/realtime-backbone.git",
9
+ "directory": "ts/client"
10
+ },
11
+ "homepage": "https://github.com/mjczone/realtime-backbone#readme",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "sideEffects": false,
23
+ "dependencies": {
24
+ "centrifuge": "5.7.4",
25
+ "@mjczone/realtime-contract": "0.0.0"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "test": "vitest run --passWithNoTests"
30
+ }
6
31
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.