@chat-leo/chatleolib 0.0.0-stage → 2.0.1

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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -2
  3. package/dist/ChatLeoWorker.d.ts +83 -0
  4. package/dist/ChatLeoWorker.d.ts.map +1 -0
  5. package/dist/ChatLeoWorker.js +255 -0
  6. package/dist/ChatLeoWorker.js.map +1 -0
  7. package/dist/ChatRoom.d.ts +121 -0
  8. package/dist/ChatRoom.d.ts.map +1 -0
  9. package/dist/ChatRoom.js +416 -0
  10. package/dist/ChatRoom.js.map +1 -0
  11. package/dist/ChatStore.d.ts +252 -0
  12. package/dist/ChatStore.d.ts.map +1 -0
  13. package/dist/ChatStore.js +774 -0
  14. package/dist/ChatStore.js.map +1 -0
  15. package/dist/JwtUtils.d.ts +39 -0
  16. package/dist/JwtUtils.d.ts.map +1 -0
  17. package/dist/JwtUtils.js +89 -0
  18. package/dist/JwtUtils.js.map +1 -0
  19. package/dist/Outbox.d.ts +68 -0
  20. package/dist/Outbox.d.ts.map +1 -0
  21. package/dist/Outbox.js +253 -0
  22. package/dist/Outbox.js.map +1 -0
  23. package/dist/UploadManager.d.ts +80 -0
  24. package/dist/UploadManager.d.ts.map +1 -0
  25. package/dist/UploadManager.js +204 -0
  26. package/dist/UploadManager.js.map +1 -0
  27. package/dist/chatleo-push-sw.js +149 -0
  28. package/dist/chatleo-push-sw.js.map +1 -0
  29. package/dist/index.d.ts +236 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.esm.js +8526 -0
  32. package/dist/index.esm.js.map +1 -0
  33. package/dist/index.js +8535 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/index.umd.js +8541 -0
  36. package/dist/index.umd.js.map +1 -0
  37. package/dist/push/PushService.d.ts +32 -0
  38. package/dist/push/PushService.d.ts.map +1 -0
  39. package/dist/push/PushService.js +215 -0
  40. package/dist/push/PushService.js.map +1 -0
  41. package/dist/push-sw/index.d.ts +9 -0
  42. package/dist/push-sw/index.d.ts.map +1 -0
  43. package/dist/push-sw/index.js +142 -0
  44. package/dist/push-sw/index.js.map +1 -0
  45. package/dist/push-sw/standalone.d.ts +2 -0
  46. package/dist/push-sw/standalone.d.ts.map +1 -0
  47. package/dist/push-sw/standalone.js +3 -0
  48. package/dist/push-sw/standalone.js.map +1 -0
  49. package/dist/transport/SocketIoTransport.d.ts +37 -0
  50. package/dist/transport/SocketIoTransport.d.ts.map +1 -0
  51. package/dist/transport/SocketIoTransport.js +209 -0
  52. package/dist/transport/SocketIoTransport.js.map +1 -0
  53. package/dist/transport/WsV2Transport.d.ts +109 -0
  54. package/dist/transport/WsV2Transport.d.ts.map +1 -0
  55. package/dist/transport/WsV2Transport.js +604 -0
  56. package/dist/transport/WsV2Transport.js.map +1 -0
  57. package/dist/transport/discovery.d.ts +43 -0
  58. package/dist/transport/discovery.d.ts.map +1 -0
  59. package/dist/transport/discovery.js +87 -0
  60. package/dist/transport/discovery.js.map +1 -0
  61. package/dist/transport/factory.d.ts +38 -0
  62. package/dist/transport/factory.d.ts.map +1 -0
  63. package/dist/transport/factory.js +79 -0
  64. package/dist/transport/factory.js.map +1 -0
  65. package/dist/transport/index.d.ts +7 -0
  66. package/dist/transport/index.d.ts.map +1 -0
  67. package/dist/transport/index.js +5 -0
  68. package/dist/transport/index.js.map +1 -0
  69. package/dist/transport/types.d.ts +174 -0
  70. package/dist/transport/types.d.ts.map +1 -0
  71. package/dist/transport/types.js +35 -0
  72. package/dist/transport/types.js.map +1 -0
  73. package/dist/transport/util.d.ts +8 -0
  74. package/dist/transport/util.d.ts.map +1 -0
  75. package/dist/transport/util.js +33 -0
  76. package/dist/transport/util.js.map +1 -0
  77. package/dist/types/shared.d.ts +281 -0
  78. package/dist/types/shared.d.ts.map +1 -0
  79. package/dist/types/shared.js +2 -0
  80. package/dist/types/shared.js.map +1 -0
  81. package/dist/types/uploads.d.ts +14 -0
  82. package/dist/types/uploads.d.ts.map +1 -0
  83. package/dist/types/uploads.js +3 -0
  84. package/dist/types/uploads.js.map +1 -0
  85. package/package.json +70 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024
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.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # chatleolib
2
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.
3
+ Core library of ChatLeo: login, real-time connection, state (`ChatStore`) and uploads. It is loaded by `<chatleo-component>` and rarely used directly.
4
+
5
+ ## Real-time transport
6
+
7
+ The library talks to the server through a `Transport` (`src/transport/`):
8
+
9
+ | Transport | Protocol |
10
+ |---|---|
11
+ | `SocketIoTransport` | Socket.IO (`socketio-v1`) — the default |
12
+ | `WsV2Transport` | ChatLeo Protocol v2 over WebSocket (`chatleo-v2`) |
13
+
14
+ ### Configuration
15
+
16
+ ```ts
17
+ import { ChatLeoLib } from '@chat-leo/chatleolib';
18
+
19
+ ChatLeoLib.transport = 'auto'; // 'socketio' (default) | 'v2' | 'auto'
20
+ ```
21
+
22
+ or, per component, `<chatleo-component transport="auto">` (takes precedence over the static setting).
23
+
24
+ * **`socketio`** — Socket.IO at `serverUrl`. Nothing else is requested; existing deployments are unaffected.
25
+ * **`v2`** — ChatLeo Protocol v2 only. The endpoint comes from discovery, or `<serverUrl>/v2/ws` if the server has no discovery document. If the WebSocket cannot be established, login still succeeds and the connection keeps retrying in the background.
26
+ * **`auto`** — after login the library fetches `GET /.well-known/chatleo` (cached for the session). If it lists `chatleo-v2`, v2 is used at the advertised URL (REST calls stay on `serverUrl`, even if the WebSocket lives on another host). If the document is missing, invalid or does not offer v2, Socket.IO is used. If v2 cannot be established after 3 attempts the library logs a warning and falls back to Socket.IO when the document lists it.
27
+
28
+ Set the value before the first login. To roll back to the previous behaviour use `socketio`.
29
+
30
+ ### Reliable sending and unread state
31
+
32
+ * `sendChatMessage()` shows the message immediately with `delivery: 'pending'` and returns the generated `client_id`. On ack the message becomes `sent` and takes the server `id`/`seq`; broadcasts that arrive first are merged by `client_id`, so nothing is shown twice.
33
+ * Failed sends stay in an `Outbox` and are retried automatically after reconnect with the same `client_id` (10 s ack timeout, exponential backoff, 5 attempts). `forbidden`, `read_only`, `not_found` and `invalid` are permanent. On failure the message has `delivery: 'failed'` and `error`; components emit `messageRetry`/`messageDiscard`, which map to `chatStore.retryMessage()`/`discardMessage()`.
34
+ * When the server sequences messages, reconnect catch-up uses one `POST /api/v1/sync` request with per-room cursors. Missing sequences are fetched with `after_seq`, scroll-back uses `before_seq`, and unread counts/read markers come from the server (`POST /rooms/:id/read`, `room-read` events). Opening the active room reports the read marker after a 2 s debounce while the tab is visible.
35
+ * Servers without sequencing keep the previous behaviour (active-room re-fetch, local unread counting) while still showing pending/sent state.
36
+
37
+ ### What differs between protocols
38
+
39
+ Sending, receiving, room events, presence, read state and catch-up sync behave identically (the same behaviour tests run against both). Only v2 additionally provides:
40
+
41
+ * **Resume** — on every reconnect the library sends its per-room cursors so the server replays missed messages; `room.resync` triggers a REST catch-up.
42
+ * **In-band token refresh** — a refreshed access token is sent as `auth.refresh` on the open connection instead of reconnecting.
43
+ * **Activity and streams** — `ChatStore` dispatches `activity` and `streamUpdated` events (typing / thinking / tool use of agents, and messages that are produced incrementally). With Socket.IO these events are never produced.
44
+
45
+ ```ts
46
+ chatStore.addEventListener('activity', (e) => {
47
+ const { roomId, senderId, kind, state, expiresAt, data } = (e as CustomEvent).detail;
48
+ });
49
+ chatStore.addEventListener('streamUpdated', (e) => {
50
+ const { streamId, roomId, text, status } = (e as CustomEvent).detail; // status: streaming | ended | aborted
51
+ });
52
+ chatStore.getActivities(roomId); // currently active activities
53
+ chatStore.getStreams(roomId); // streams in progress
54
+ ```
55
+
56
+ ### Testing
57
+
58
+ ```bash
59
+ pnpm --filter @chat-leo/chatleolib test
60
+ ```
61
+
62
+ `behaviour.socketio.test.ts` and `behaviour.v2.test.ts` run one shared scenario suite (`src/testing/behaviourSuite.ts`) against a fake Socket.IO server and a fake v2 server. `src/testing/FakeV2Server.ts` can be reused to test other v2 clients.
63
+
64
+
65
+ ### Calls (protocol v2 only)
66
+ Calls require protocol v2. On Socket.IO the library reports calls as unavailable, ignores call events and refuses the call REST actions; chat keeps working. `ChatStore` exposes `activeCall(roomId)` and `incomingCall`, and dispatches `callChanged` / `callRinging`. `ChatLeoLib.ensureCallsAvailable()` checks the discovery `calls` feature; `startCall`, `joinCall`, `declineCall`, `leaveCall`, `endCall` and `refreshCallToken` call `/api/v1/.../calls`. `joinCall` returns `{sfu_url, token, room_id, mode, ice_servers}`, which maps directly to `call-core`'s `ConnectionCredentials`. Call state also comes from `active_call` in the room list and sync response, so a client that missed live events still shows a running call.
67
+
68
+
69
+ ### Push notifications
70
+ `ChatLeoLib.push` exposes `state()`, `enable()`, `disable()` and `syncOnLogin()`; the component uses `pushState`, `enablePush` and `disablePush`. Push requires the server's `push` discovery feature and a served worker (`chatleolib/dist/chatleo-push-sw.js`, or import `chatleolib/push-sw` into an existing worker). Subscriptions always go through the ChatLeo server; the PulseLeo SDK is loaded lazily. See `docs/push.md`.
@@ -0,0 +1,83 @@
1
+ /**
2
+ * ChatLeoWorker — SharedWorker entry point.
3
+ *
4
+ * Manages one real-time `Transport` (Socket.IO or ChatLeo Protocol v2) and one token-refresh
5
+ * loop **per session**. Sessions are isolated by a key derived from (serverUrl + accountId) so
6
+ * that multiple tenant logins on the same origin never share a connection or tokens.
7
+ *
8
+ * Tabs communicate over MessagePort; normalised transport events are routed ONLY to the ports
9
+ * belonging to the matching session key.
10
+ *
11
+ * Usage is opt-in (feature-flagged in ChatLeoLib). Falls back to per-tab
12
+ * connection when SharedWorker is unavailable.
13
+ */
14
+ import { TransportChoice } from './transport/factory';
15
+ import type { Cursors, Transport, TransportCommand, TransportEvent } from './transport/types';
16
+ export type WorkerInbound = {
17
+ type: 'attach';
18
+ sessionKey: string;
19
+ serverUrl: string;
20
+ accessToken: string;
21
+ refreshToken: string;
22
+ accountId: string;
23
+ /** Protocol/endpoint chosen by the tab (defaults to Socket.IO at `serverUrl`). */
24
+ transport?: TransportChoice;
25
+ /** Used when `transport` cannot be established. */
26
+ fallback?: TransportChoice;
27
+ cursors?: Cursors;
28
+ } | {
29
+ type: 'detach';
30
+ sessionKey: string;
31
+ } | {
32
+ type: 'request';
33
+ sessionKey: string;
34
+ requestId: string;
35
+ command: TransportCommand;
36
+ } | {
37
+ type: 'ping';
38
+ sessionKey: string;
39
+ };
40
+ export type WorkerOutbound = {
41
+ type: 'connectionStatus';
42
+ status: string;
43
+ } | {
44
+ type: 'transportEvent';
45
+ event: TransportEvent;
46
+ } | {
47
+ type: 'response';
48
+ requestId: string;
49
+ ok: boolean;
50
+ result?: unknown;
51
+ error?: string;
52
+ } | {
53
+ type: 'tokenRefreshed';
54
+ accessToken: string;
55
+ } | {
56
+ type: 'sessionExpired';
57
+ } | {
58
+ type: 'pong';
59
+ };
60
+ interface Session {
61
+ serverUrl: string;
62
+ accessToken: string;
63
+ refreshToken: string;
64
+ accountId: string;
65
+ plan: {
66
+ primary: TransportChoice;
67
+ fallback?: TransportChoice;
68
+ };
69
+ transport: Transport | null;
70
+ unsubscribe: (() => void) | null;
71
+ ports: Set<MessagePort>;
72
+ refreshTimer: ReturnType<typeof setTimeout> | null;
73
+ isRefreshing: boolean;
74
+ retryCount: number;
75
+ graceTeardownTimer: ReturnType<typeof setTimeout> | null;
76
+ }
77
+ export declare const sessions: Map<string, Session>;
78
+ /** Test hook: replace how transports are created. */
79
+ export declare function setTransportFactory(f: (choice: TransportChoice) => Transport): void;
80
+ export declare function refreshSessionToken(sessionKey: string): Promise<void>;
81
+ export declare function handleMessage(port: MessagePort, msg: WorkerInbound): void;
82
+ export {};
83
+ //# sourceMappingURL=ChatLeoWorker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatLeoWorker.d.ts","sourceRoot":"","sources":["../src/ChatLeoWorker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAwC,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAM9F,MAAM,MAAM,aAAa,GACrB;IACE,IAAI,EAAE,QAAQ,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IACpH,kFAAkF;IAClF,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,mDAAmD;IACnD,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GACD;IAAE,IAAI,EAAE,QAA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IACnD,YAAY,EAAE,OAAO,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,kBAAkB,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAC;CAC1D;AAMD,eAAO,MAAM,QAAQ,sBAA6B,CAAC;AAMnD,qDAAqD;AACrD,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,SAAS,QAE5E;AAoFD,wBAAsB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqD3E;AAMD,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,aAAa,QAwElE"}
@@ -0,0 +1,255 @@
1
+ /**
2
+ * ChatLeoWorker — SharedWorker entry point.
3
+ *
4
+ * Manages one real-time `Transport` (Socket.IO or ChatLeo Protocol v2) and one token-refresh
5
+ * loop **per session**. Sessions are isolated by a key derived from (serverUrl + accountId) so
6
+ * that multiple tenant logins on the same origin never share a connection or tokens.
7
+ *
8
+ * Tabs communicate over MessagePort; normalised transport events are routed ONLY to the ports
9
+ * belonging to the matching session key.
10
+ *
11
+ * Usage is opt-in (feature-flagged in ChatLeoLib). Falls back to per-tab
12
+ * connection when SharedWorker is unavailable.
13
+ */
14
+ import { calculateRefreshDelay } from './JwtUtils';
15
+ import { connectWithFallback, createTransport } from './transport/factory';
16
+ // ---------------------------------------------------------------------------
17
+ // Session registry (key → Session)
18
+ // ---------------------------------------------------------------------------
19
+ export const sessions = new Map();
20
+ const MAX_REFRESH_RETRIES = 5;
21
+ const TEARDOWN_GRACE_MS = 5000;
22
+ let transportFactory = createTransport;
23
+ /** Test hook: replace how transports are created. */
24
+ export function setTransportFactory(f) {
25
+ transportFactory = f;
26
+ }
27
+ // ---------------------------------------------------------------------------
28
+ // Session helpers
29
+ // ---------------------------------------------------------------------------
30
+ function broadcastToSession(sessionKey, msg) {
31
+ const session = sessions.get(sessionKey);
32
+ if (!session)
33
+ return;
34
+ for (const port of session.ports) {
35
+ try {
36
+ port.postMessage(msg);
37
+ }
38
+ catch (_a) {
39
+ session.ports.delete(port);
40
+ }
41
+ }
42
+ }
43
+ function connectSession(sessionKey, cursors) {
44
+ const session = sessions.get(sessionKey);
45
+ if (!session || session.transport)
46
+ return;
47
+ broadcastToSession(sessionKey, { type: 'connectionStatus', status: 'connecting' });
48
+ connectWithFallback(session.plan, { token: session.accessToken, cursors }, (transport, previous) => {
49
+ var _a;
50
+ if (previous) {
51
+ (_a = session.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(session);
52
+ }
53
+ session.transport = transport;
54
+ session.unsubscribe = transport.on((event) => {
55
+ if (event.type === 'status') {
56
+ broadcastToSession(sessionKey, { type: 'connectionStatus', status: event.status });
57
+ }
58
+ else if (event.type === 'authRequired') {
59
+ // The worker owns the refresh token; tabs never see this event.
60
+ refreshSessionToken(sessionKey).catch(() => { });
61
+ }
62
+ else {
63
+ broadcastToSession(sessionKey, { type: 'transportEvent', event });
64
+ }
65
+ });
66
+ }, transportFactory).catch((err) => console.warn('[ChatLeoWorker] initial connect failed', err));
67
+ }
68
+ function teardownSession(sessionKey) {
69
+ var _a, _b;
70
+ const session = sessions.get(sessionKey);
71
+ if (!session)
72
+ return;
73
+ clearRefreshTimer(session);
74
+ (_a = session.transport) === null || _a === void 0 ? void 0 : _a.close();
75
+ (_b = session.unsubscribe) === null || _b === void 0 ? void 0 : _b.call(session);
76
+ session.transport = null;
77
+ sessions.delete(sessionKey);
78
+ }
79
+ function scheduleGraceTeardown(sessionKey) {
80
+ const session = sessions.get(sessionKey);
81
+ if (!session)
82
+ return;
83
+ if (session.graceTeardownTimer)
84
+ clearTimeout(session.graceTeardownTimer);
85
+ session.graceTeardownTimer = setTimeout(() => {
86
+ const s = sessions.get(sessionKey);
87
+ if (s && s.ports.size === 0)
88
+ teardownSession(sessionKey);
89
+ }, TEARDOWN_GRACE_MS);
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // Token refresh
93
+ // ---------------------------------------------------------------------------
94
+ function clearRefreshTimer(session) {
95
+ if (session.refreshTimer) {
96
+ clearTimeout(session.refreshTimer);
97
+ session.refreshTimer = null;
98
+ }
99
+ }
100
+ function scheduleTokenRefresh(sessionKey) {
101
+ const session = sessions.get(sessionKey);
102
+ if (!session || !session.accessToken)
103
+ return;
104
+ clearRefreshTimer(session);
105
+ const delay = calculateRefreshDelay(session.accessToken);
106
+ if (delay === null)
107
+ return;
108
+ session.refreshTimer = setTimeout(() => {
109
+ refreshSessionToken(sessionKey).catch(() => { });
110
+ }, delay);
111
+ }
112
+ export async function refreshSessionToken(sessionKey) {
113
+ var _a;
114
+ const session = sessions.get(sessionKey);
115
+ if (!session || session.isRefreshing)
116
+ return;
117
+ if (!session.refreshToken) {
118
+ broadcastToSession(sessionKey, { type: 'sessionExpired' });
119
+ teardownSession(sessionKey);
120
+ return;
121
+ }
122
+ session.isRefreshing = true;
123
+ try {
124
+ const response = await fetch(`${session.serverUrl}/api/v1/auth/refresh`, {
125
+ method: 'POST',
126
+ headers: { 'Content-Type': 'application/json' },
127
+ body: JSON.stringify({ refresh_token: session.refreshToken }),
128
+ });
129
+ if (!response.ok) {
130
+ if (response.status === 401 || response.status === 403) {
131
+ broadcastToSession(sessionKey, { type: 'sessionExpired' });
132
+ teardownSession(sessionKey);
133
+ return;
134
+ }
135
+ throw new Error(`Refresh failed ${response.status}`);
136
+ }
137
+ const data = await response.json();
138
+ session.accessToken = data.access_token;
139
+ if (data.refresh_token)
140
+ session.refreshToken = data.refresh_token;
141
+ session.retryCount = 0;
142
+ // v2: in-band auth.refresh; Socket.IO: credentials for the next handshake (reconnects after an auth failure)
143
+ await ((_a = session.transport) === null || _a === void 0 ? void 0 : _a.updateToken(session.accessToken).catch((err) => {
144
+ console.warn('[ChatLeoWorker] transport.updateToken failed', err);
145
+ }));
146
+ broadcastToSession(sessionKey, { type: 'tokenRefreshed', accessToken: session.accessToken });
147
+ scheduleTokenRefresh(sessionKey);
148
+ }
149
+ catch (_b) {
150
+ session.retryCount++;
151
+ if (session.retryCount >= MAX_REFRESH_RETRIES) {
152
+ broadcastToSession(sessionKey, { type: 'sessionExpired' });
153
+ teardownSession(sessionKey);
154
+ return;
155
+ }
156
+ const delay = Math.min(5000 * Math.pow(2, session.retryCount - 1), 60000);
157
+ session.refreshTimer = setTimeout(() => {
158
+ refreshSessionToken(sessionKey).catch(() => { });
159
+ }, delay);
160
+ }
161
+ finally {
162
+ const s = sessions.get(sessionKey);
163
+ if (s)
164
+ s.isRefreshing = false;
165
+ }
166
+ }
167
+ // ---------------------------------------------------------------------------
168
+ // Port message handling
169
+ // ---------------------------------------------------------------------------
170
+ export function handleMessage(port, msg) {
171
+ var _a, _b, _c, _d;
172
+ const { type } = msg;
173
+ if (type === 'attach') {
174
+ const { sessionKey, serverUrl, accessToken, refreshToken, accountId } = msg;
175
+ let session = sessions.get(sessionKey);
176
+ if (!session) {
177
+ session = {
178
+ serverUrl,
179
+ accessToken,
180
+ refreshToken,
181
+ accountId,
182
+ plan: { primary: (_a = msg.transport) !== null && _a !== void 0 ? _a : { kind: 'socketio', url: serverUrl, serverUrl }, fallback: msg.fallback },
183
+ transport: null,
184
+ unsubscribe: null,
185
+ ports: new Set(),
186
+ refreshTimer: null,
187
+ isRefreshing: false,
188
+ retryCount: 0,
189
+ graceTeardownTimer: null,
190
+ };
191
+ sessions.set(sessionKey, session);
192
+ session.ports.add(port);
193
+ connectSession(sessionKey, msg.cursors);
194
+ scheduleTokenRefresh(sessionKey);
195
+ }
196
+ else {
197
+ // Cancel any pending teardown for this session
198
+ if (session.graceTeardownTimer) {
199
+ clearTimeout(session.graceTeardownTimer);
200
+ session.graceTeardownTimer = null;
201
+ }
202
+ // Update tokens in case they changed (e.g. tab re-authed)
203
+ session.accessToken = accessToken;
204
+ session.refreshToken = refreshToken;
205
+ (_b = session.transport) === null || _b === void 0 ? void 0 : _b.updateToken(accessToken).catch(() => { });
206
+ }
207
+ session.ports.add(port);
208
+ // Immediately send current connection status
209
+ port.postMessage({ type: 'connectionStatus', status: (_d = (_c = session.transport) === null || _c === void 0 ? void 0 : _c.status) !== null && _d !== void 0 ? _d : 'disconnected' });
210
+ return;
211
+ }
212
+ if (type === 'detach') {
213
+ const session = sessions.get(msg.sessionKey);
214
+ if (session) {
215
+ session.ports.delete(port);
216
+ if (session.ports.size === 0)
217
+ scheduleGraceTeardown(msg.sessionKey);
218
+ }
219
+ return;
220
+ }
221
+ if (type === 'request') {
222
+ const session = sessions.get(msg.sessionKey);
223
+ const reply = (r) => port.postMessage({ type: 'response', requestId: msg.requestId, ...r });
224
+ if (!(session === null || session === void 0 ? void 0 : session.transport)) {
225
+ reply({ ok: false, error: 'not connected' });
226
+ return;
227
+ }
228
+ session.transport.request(msg.command).then((result) => reply({ ok: true, result }), (err) => { var _a; return reply({ ok: false, error: (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : String(err) }); });
229
+ return;
230
+ }
231
+ if (type === 'ping') {
232
+ port.postMessage({ type: 'pong' });
233
+ return;
234
+ }
235
+ }
236
+ // ---------------------------------------------------------------------------
237
+ // SharedWorker connect handler
238
+ // ---------------------------------------------------------------------------
239
+ // @ts-ignore — SharedWorker global
240
+ self.onconnect = (connectEvent) => {
241
+ const port = connectEvent.ports[0];
242
+ port.onmessage = (e) => {
243
+ try {
244
+ handleMessage(port, e.data);
245
+ }
246
+ catch (err) {
247
+ console.error('[ChatLeoWorker] handleMessage error', err);
248
+ }
249
+ };
250
+ port.onmessageerror = (err) => {
251
+ console.error('[ChatLeoWorker] port message error', err);
252
+ };
253
+ port.start();
254
+ };
255
+ //# sourceMappingURL=ChatLeoWorker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatLeoWorker.js","sourceRoot":"","sources":["../src/ChatLeoWorker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,E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,GAAG,CAAC,CAAC;IAC3D,CAAC,CAAC;IAEF,IAAI,CAAC,KAAK,EAAE,CAAC;AACf,CAAC,CAAC"}
@@ -0,0 +1,121 @@
1
+ import { ChatLeoMessage, NotificationLevel, RoomSummary, RoomType, UserProfile } from "./types/shared";
2
+ /** Result of inserting a message into a room. */
3
+ export interface AddMessageResult {
4
+ message: ChatLeoMessage;
5
+ added: boolean;
6
+ /** The message already existed and its fields were merged (echo/ack of a local send). */
7
+ updated: boolean;
8
+ }
9
+ /**
10
+ * @class ChatRoom
11
+ * @extends EventTarget
12
+ * @description This class represents a single chat room. It manages the messages and participants
13
+ * for the room and dispatches events when participants are added or messages are received.
14
+ *
15
+ * Messages are kept sorted by `seq` (when both sides have one), otherwise by `created_at`.
16
+ * Duplicates are removed by `id` and by the local sender's `client_id`. The room also tracks the
17
+ * last contiguous `seq` it holds so the client can resume synchronisation and detect gaps.
18
+ */
19
+ export declare class ChatRoom extends EventTarget {
20
+ #private;
21
+ readonly id: string;
22
+ type: RoomType;
23
+ unreadCount: number;
24
+ notificationLevel: NotificationLevel;
25
+ /**
26
+ * @constructor
27
+ * @param {string} id - The unique identifier for the room.
28
+ * @param {string} _name - The name of the room.
29
+ * @param {RoomType} type - The type of the room (e.g., 'DirectMessage', 'Group').
30
+ * @param {string[]} _participants - An array of user IDs for the participants in the room.
31
+ * @param {string} _localId - The ID of the local user.
32
+ */
33
+ constructor(id: string, _name: string, type: RoomType, _participants: string[], _localId: string, _isReadOnly?: boolean, _unreadCount?: number);
34
+ /**
35
+ * @method setUsernameResolver
36
+ * @description Sets a function that can be used to resolve a user's profile from their ID. This is used to get the display name for direct message rooms.
37
+ * @param {function} resolver - A function that takes a user ID and returns a `UserProfile` object or `undefined`.
38
+ */
39
+ setUsernameResolver(resolver: (id: string) => UserProfile | undefined): void;
40
+ /**
41
+ * @method fromRoomSummary
42
+ * @description A static factory method that creates a new `ChatRoom` instance from a `RoomSummary` object.
43
+ * @param {RoomSummary} summary - The `RoomSummary` object containing the room's data.
44
+ * @param {string} localId - The ID of the local user.
45
+ * @returns {ChatRoom} A new `ChatRoom` instance.
46
+ */
47
+ static fromRoomSummary(summary: RoomSummary, localId: string): ChatRoom;
48
+ /**
49
+ * @method includes
50
+ * @description Checks if a given user ID is a participant in the room.
51
+ * @param {string} participant - The user ID to check.
52
+ * @returns {boolean} `true` if the user is a participant, `false` otherwise.
53
+ */
54
+ includes(participant: string): boolean;
55
+ /**
56
+ * @method addParticipant
57
+ * @description Adds a new participant to the room and dispatches a `participantAdded` event.
58
+ * @param {string} participant - The user ID of the participant to add.
59
+ */
60
+ addParticipant(participant: string): void;
61
+ /**
62
+ * @method addMessage
63
+ * @description Adds a single message to the room's message list and dispatches a `messageAdded`
64
+ * (or `messageUpdated` when an echo/ack merged into a local message).
65
+ */
66
+ addMessage(msg: ChatLeoMessage, isLive?: boolean): ChatLeoMessage;
67
+ /**
68
+ * @method addMessages
69
+ * @description Adds an array of messages (history, sync or a page of older messages). Dispatches
70
+ * one event for the whole batch so the UI does not re-render per message.
71
+ */
72
+ addMessages(msgs: ChatLeoMessage[], isLive?: boolean): void;
73
+ /**
74
+ * @method ackMessage
75
+ * @description Marks a pending local message as delivered and takes the server `id`, `seq` and
76
+ * `created_at`. Safe to call after the broadcast already arrived (matched by `client_id`).
77
+ */
78
+ ackMessage(clientId: string, ack: {
79
+ id?: string;
80
+ seq?: number;
81
+ createdAt?: string;
82
+ }): void;
83
+ /** Marks a local message as permanently failed and stores the reason. */
84
+ failMessage(clientId: string, reason: string): void;
85
+ /** Puts a failed local message back into the outbox (state becomes `pending`). */
86
+ markMessagePending(clientId: string): void;
87
+ /** Removes a local message that was discarded by the user. */
88
+ removeMessageByClientId(clientId: string): void;
89
+ markAsRead(seq?: number): void;
90
+ /** Applies a read marker from another device without reporting it back to the server. */
91
+ applyRemoteRead(seq?: number): void;
92
+ /** Confirms a marker this client sent; does not dispatch `roomRead` (avoids a feedback loop). */
93
+ confirmRead(seq: number): void;
94
+ setNotificationLevel(level: NotificationLevel): void;
95
+ setUnreadCount(count: number): void;
96
+ /** Applies server-side room metadata from a room list or sync response. */
97
+ setServerMeta(meta: {
98
+ lastSeq?: number;
99
+ lastReadSeq?: number;
100
+ unreadCount?: number;
101
+ }): void;
102
+ get isReadOnly(): boolean;
103
+ get name(): string;
104
+ get participantIds(): string[];
105
+ get participantIdsWithoutSelf(): string[];
106
+ get messages(): ChatLeoMessage[];
107
+ /** Highest `seq` held locally (0 when nothing sequenced is loaded). */
108
+ get lastSeq(): number;
109
+ /** Highest `seq` the server reported for this room (may be ahead of what is loaded). */
110
+ get serverLastSeq(): number;
111
+ /** Highest `seq` such that every sequence from the loaded range up to it is present. */
112
+ get contiguousSeq(): number;
113
+ get lastReadSeq(): number | undefined;
114
+ /** Lowest `seq` currently held, used for scroll-back paging. */
115
+ get oldestSeq(): number | undefined;
116
+ /** Oldest `created_at` held, used for scroll-back against legacy servers. */
117
+ get oldestCreatedAt(): string | undefined;
118
+ /** True when `seq` is beyond the contiguous range and the missing range must be fetched. */
119
+ hasGapBefore(seq: number): boolean;
120
+ }
121
+ //# sourceMappingURL=ChatRoom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatRoom.d.ts","sourceRoot":"","sources":["../src/ChatRoom.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,cAAc,EAAE,iBAAiB,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAErG,iDAAiD;AACjD,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,cAAc,CAAC;IACxB,KAAK,EAAE,OAAO,CAAC;IACf,yFAAyF;IACzF,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;GASG;AACH,qBAAa,QAAS,SAAQ,WAAW;;aA2BrB,EAAE,EAAE,MAAM;IAEnB,IAAI,EAAE,QAAQ;IAfhB,WAAW,EAAE,MAAM,CAAK;IACxB,iBAAiB,EAAE,iBAAiB,CAAS;I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