@abraca/dabra 2.90.0 → 2.91.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/package.json +5 -11
- package/src/AbracadabraBaseProvider.ts +0 -963
- package/src/AbracadabraClient.ts +0 -1960
- package/src/AbracadabraProvider.ts +0 -915
- package/src/AbracadabraWS.ts +0 -695
- package/src/BackgroundSyncManager.ts +0 -856
- package/src/BackgroundSyncPersistence.ts +0 -140
- package/src/ChatClient.ts +0 -314
- package/src/CloseEvents.ts +0 -49
- package/src/ContentManager.ts +0 -246
- package/src/CoverReconcile.ts +0 -168
- package/src/CryptoIdentityKeystore.ts +0 -754
- package/src/DeviceRegistrationService.ts +0 -257
- package/src/DocConverters.ts +0 -1859
- package/src/DocKeyManager.ts +0 -163
- package/src/DocTypes.ts +0 -628
- package/src/DocUtils.ts +0 -251
- package/src/DocumentCache.ts +0 -210
- package/src/DocumentManager.ts +0 -410
- package/src/E2EAbracadabraProvider.ts +0 -426
- package/src/E2EOfflineStore.ts +0 -55
- package/src/EncryptedChatClient.ts +0 -173
- package/src/EncryptedY.ts +0 -145
- package/src/EventEmitter.ts +0 -59
- package/src/FileBlobStore.ts +0 -569
- package/src/IdentityDoc.ts +0 -711
- package/src/IncomingMessage.ts +0 -63
- package/src/MessageReceiver.ts +0 -151
- package/src/MessageSender.ts +0 -22
- package/src/MetaManager.ts +0 -194
- package/src/MnemonicKeyDerivation.ts +0 -171
- package/src/NodeConnect.ts +0 -63
- package/src/NodeIdentity.ts +0 -378
- package/src/NotificationsClient.ts +0 -207
- package/src/OfflineStore.ts +0 -294
- package/src/OutgoingMessage.ts +0 -25
- package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
- package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
- package/src/OutgoingMessages/CloseMessage.ts +0 -17
- package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
- package/src/OutgoingMessages/StatelessMessage.ts +0 -18
- package/src/OutgoingMessages/SubdocMessage.ts +0 -35
- package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
- package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
- package/src/OutgoingMessages/UpdateMessage.ts +0 -20
- package/src/QueryClient.ts +0 -209
- package/src/RpcClient.ts +0 -659
- package/src/SchemaTypes.ts +0 -179
- package/src/SearchIndex.ts +0 -250
- package/src/ServerRegistry.ts +0 -220
- package/src/ServerReset.ts +0 -222
- package/src/TokenManager.ts +0 -337
- package/src/TreeManager.ts +0 -894
- package/src/TreeTimestamps.ts +0 -101
- package/src/auth.ts +0 -62
- package/src/awarenessStatesToArray.ts +0 -10
- package/src/index.ts +0 -219
- package/src/messageRecord.ts +0 -121
- package/src/sync/BroadcastChannelSync.ts +0 -235
- package/src/types.ts +0 -790
- package/src/webrtc/AbracadabraWebRTC.ts +0 -683
- package/src/webrtc/DataChannelRouter.ts +0 -179
- package/src/webrtc/DevicePairingChannel.ts +0 -496
- package/src/webrtc/E2EEChannel.ts +0 -195
- package/src/webrtc/FileTransferChannel.ts +0 -367
- package/src/webrtc/ManualSignaling.ts +0 -204
- package/src/webrtc/PeerConnection.ts +0 -133
- package/src/webrtc/SignalingSocket.ts +0 -378
- package/src/webrtc/YjsDataChannel.ts +0 -203
- package/src/webrtc/index.ts +0 -26
- package/src/webrtc/types.ts +0 -177
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BackgroundSyncPersistence
|
|
3
|
-
*
|
|
4
|
-
* Minimal IndexedDB store (`abracadabra:bgsync:{serverOrigin}`) that persists
|
|
5
|
-
* per-document sync state across page reloads. A single object store,
|
|
6
|
-
* `sync_state`, is keyed by `docId`.
|
|
7
|
-
*
|
|
8
|
-
* Falls back to a no-op when IndexedDB is unavailable (SSR / Node.js).
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Background-sync lifecycle status.
|
|
13
|
-
*
|
|
14
|
-
* - `pending` — never synced; queued for first attempt.
|
|
15
|
-
* - `syncing` — attempt in progress (transient, not persisted as terminal).
|
|
16
|
-
* - `synced` — last attempt succeeded; `lastSynced` is set.
|
|
17
|
-
* - `retrying` — a *transient* failure (timeout, network) that has NOT yet
|
|
18
|
-
* crossed the failure threshold. Will be retried silently;
|
|
19
|
-
* the UI should treat this calmly and NOT count it as an error.
|
|
20
|
-
* - `error` — a transient failure that has recurred past the threshold
|
|
21
|
-
* (`consecutiveFailures >= FAILURE_THRESHOLD`). Genuinely
|
|
22
|
-
* needs attention; this is what the UI surfaces as red.
|
|
23
|
-
* - `unavailable` — a *permanent* failure (doc deleted/forbidden/invalid id —
|
|
24
|
-
* 404/403/410/422). Not retried, and not surfaced as an error.
|
|
25
|
-
* - `skipped` — E2E doc we can't sync (no keystore). Benign.
|
|
26
|
-
*/
|
|
27
|
-
export type DocSyncStatus =
|
|
28
|
-
| "pending"
|
|
29
|
-
| "syncing"
|
|
30
|
-
| "synced"
|
|
31
|
-
| "retrying"
|
|
32
|
-
| "error"
|
|
33
|
-
| "unavailable"
|
|
34
|
-
| "skipped";
|
|
35
|
-
|
|
36
|
-
export interface DocSyncState {
|
|
37
|
-
docId: string;
|
|
38
|
-
/** Current lifecycle status of this document's background sync. */
|
|
39
|
-
status: DocSyncStatus;
|
|
40
|
-
/** Unix ms of the last successful sync, or null if never synced. */
|
|
41
|
-
lastSynced: number | null;
|
|
42
|
-
/**
|
|
43
|
-
* Human-readable message for the most recent failure. Populated for
|
|
44
|
-
* `retrying`, `error`, and `unavailable` — cleared on a successful sync.
|
|
45
|
-
*/
|
|
46
|
-
error?: string;
|
|
47
|
-
/**
|
|
48
|
-
* Count of consecutive failed attempts. Reset to 0 on success. Drives the
|
|
49
|
-
* `retrying` → `error` escalation so a single transient blip never nags.
|
|
50
|
-
*/
|
|
51
|
-
consecutiveFailures?: number;
|
|
52
|
-
/** Whether the document uses E2E encryption. */
|
|
53
|
-
isE2E: boolean;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const DB_VERSION = 1;
|
|
57
|
-
|
|
58
|
-
function idbAvailable(): boolean {
|
|
59
|
-
return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
function openDb(serverOrigin: string): Promise<IDBDatabase> {
|
|
63
|
-
return new Promise((resolve, reject) => {
|
|
64
|
-
const req = globalThis.indexedDB.open(
|
|
65
|
-
`abracadabra:bgsync:${serverOrigin}`,
|
|
66
|
-
DB_VERSION,
|
|
67
|
-
);
|
|
68
|
-
req.onupgradeneeded = (event) => {
|
|
69
|
-
const db = (event.target as IDBOpenDBRequest).result;
|
|
70
|
-
if (!db.objectStoreNames.contains("sync_state")) {
|
|
71
|
-
db.createObjectStore("sync_state", { keyPath: "docId" });
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
req.onsuccess = () => resolve(req.result);
|
|
75
|
-
req.onerror = () => reject(req.error);
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function idbPromise<T>(request: IDBRequest<T>): Promise<T> {
|
|
80
|
-
return new Promise((resolve, reject) => {
|
|
81
|
-
request.onsuccess = () => resolve(request.result);
|
|
82
|
-
request.onerror = () => reject(request.error);
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export class BackgroundSyncPersistence {
|
|
87
|
-
private dbPromise: Promise<IDBDatabase | null> | null = null;
|
|
88
|
-
private readonly serverOrigin: string;
|
|
89
|
-
|
|
90
|
-
constructor(serverOrigin: string) {
|
|
91
|
-
this.serverOrigin = serverOrigin;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
private getDb(): Promise<IDBDatabase | null> {
|
|
95
|
-
if (!idbAvailable()) return Promise.resolve(null);
|
|
96
|
-
if (!this.dbPromise) {
|
|
97
|
-
this.dbPromise = openDb(this.serverOrigin).catch(() => null);
|
|
98
|
-
}
|
|
99
|
-
return this.dbPromise;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async getState(docId: string): Promise<DocSyncState | null> {
|
|
103
|
-
const db = await this.getDb();
|
|
104
|
-
if (!db) return null;
|
|
105
|
-
const tx = db.transaction("sync_state", "readonly");
|
|
106
|
-
const result = await idbPromise<DocSyncState | undefined>(
|
|
107
|
-
tx.objectStore("sync_state").get(docId),
|
|
108
|
-
);
|
|
109
|
-
return result ?? null;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async getAllStates(): Promise<DocSyncState[]> {
|
|
113
|
-
const db = await this.getDb();
|
|
114
|
-
if (!db) return [];
|
|
115
|
-
return new Promise((resolve, reject) => {
|
|
116
|
-
const tx = db.transaction("sync_state", "readonly");
|
|
117
|
-
const req = tx.objectStore("sync_state").getAll();
|
|
118
|
-
req.onsuccess = () => resolve(req.result as DocSyncState[]);
|
|
119
|
-
req.onerror = () => reject(req.error);
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async setState(state: DocSyncState): Promise<void> {
|
|
124
|
-
const db = await this.getDb();
|
|
125
|
-
if (!db) return;
|
|
126
|
-
const tx = db.transaction("sync_state", "readwrite");
|
|
127
|
-
await idbPromise(tx.objectStore("sync_state").put(state));
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
async deleteState(docId: string): Promise<void> {
|
|
131
|
-
const db = await this.getDb();
|
|
132
|
-
if (!db) return;
|
|
133
|
-
const tx = db.transaction("sync_state", "readwrite");
|
|
134
|
-
await idbPromise(tx.objectStore("sync_state").delete(docId));
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
destroy(): void {
|
|
138
|
-
// No cleanup needed — shared IDB connection managed by browser
|
|
139
|
-
}
|
|
140
|
-
}
|
package/src/ChatClient.ts
DELETED
|
@@ -1,314 +0,0 @@
|
|
|
1
|
-
import EventEmitter from "./EventEmitter.ts";
|
|
2
|
-
import type {
|
|
3
|
-
ChatTypingEvent,
|
|
4
|
-
SendChatMessageInput as _LegacySendInput,
|
|
5
|
-
GetChatHistoryInput as _LegacyHistoryInput,
|
|
6
|
-
} from "./types.ts";
|
|
7
|
-
|
|
8
|
-
// Legacy alias re-exports kept for type-import compat with consumers that
|
|
9
|
-
// import these names from `@abraca/dabra`. The old shapes still describe
|
|
10
|
-
// the wire the dashboard's own reactive layer reads/writes; this client
|
|
11
|
-
// itself no longer uses them as method inputs.
|
|
12
|
-
export type _ReExportedTypes = _LegacySendInput | _LegacyHistoryInput;
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Minimal provider surface ChatClient needs. Matches `AbracadabraBaseProvider`.
|
|
16
|
-
*/
|
|
17
|
-
export interface ChatClientTransport {
|
|
18
|
-
sendStateless(payload: string): void;
|
|
19
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
20
|
-
on(event: string, fn: Function): unknown;
|
|
21
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
22
|
-
off(event: string, fn?: Function): unknown;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
type PendingResolver<T> = {
|
|
26
|
-
resolve: (value: T) => void;
|
|
27
|
-
reject: (err: Error) => void;
|
|
28
|
-
timer: ReturnType<typeof setTimeout>;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Send a chat message into a channel doc.
|
|
35
|
-
*
|
|
36
|
-
* `channel_doc_id` is the UUID of the channel/dm doc — `documents.id` for
|
|
37
|
-
* a row with `kind = "channel"` or `kind = "dm"`. Group channels under a
|
|
38
|
-
* Space pass the channel doc's id; DMs pass the DM doc's id (callers
|
|
39
|
-
* resolve "the DM doc between user A and user B" via their own path —
|
|
40
|
-
* typically `client.listChildren(serverRootId)` filtered by `kind === "dm"`
|
|
41
|
-
* with both pubkeys in `permissions`).
|
|
42
|
-
*/
|
|
43
|
-
export interface SendMessageInput {
|
|
44
|
-
channel_doc_id: string;
|
|
45
|
-
content: string;
|
|
46
|
-
/** Cleartext recipient pubkeys for server-side mention fan-out. */
|
|
47
|
-
mentions?: string[];
|
|
48
|
-
/** Message id this is a reply to. */
|
|
49
|
-
reply_to?: string;
|
|
50
|
-
/**
|
|
51
|
-
* Optional Ed25519 signature over the canonical envelope, base64url. When
|
|
52
|
-
* server config `[messages].require_client_sig = true`, sends without a
|
|
53
|
-
* sig are rejected. Default-config servers accept unsigned sends — the
|
|
54
|
-
* threat model relies on JWT-bound session auth + the server's own
|
|
55
|
-
* `server_sig` over `(msg_id, period_id, ts, sig)`.
|
|
56
|
-
*/
|
|
57
|
-
sig?: string;
|
|
58
|
-
/** Client-side timestamp (ms) for skew-tolerance check. Optional. */
|
|
59
|
-
ts_hint?: number;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export interface SendMessageResult {
|
|
63
|
-
message_id: string;
|
|
64
|
-
period_id: string;
|
|
65
|
-
ts: number;
|
|
66
|
-
server_sig: string;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export interface EditMessageInput {
|
|
70
|
-
channel_doc_id: string;
|
|
71
|
-
message_id: string;
|
|
72
|
-
content: string;
|
|
73
|
-
sig?: string;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export interface DeleteMessageInput {
|
|
77
|
-
channel_doc_id: string;
|
|
78
|
-
message_id: string;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export interface MarkReadInput {
|
|
82
|
-
channel_doc_id: string;
|
|
83
|
-
period_id: string;
|
|
84
|
-
message_id: string;
|
|
85
|
-
/** Unix milliseconds. Defaults to server time. */
|
|
86
|
-
ts?: number;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Thin façade over the `messages:*` stateless protocol.
|
|
91
|
-
*
|
|
92
|
-
* The unified messages model stores chat history as Y.Array entries on
|
|
93
|
-
* `kind = "channel-period"` child docs of channel/dm docs (and notifications
|
|
94
|
-
* as entries on a per-user `kind = "inbox"` doc). Reading history, listing
|
|
95
|
-
* channels, observing real-time messages, and tracking read cursors are all
|
|
96
|
-
* Y.Doc-shaped operations that the SDK consumer performs via
|
|
97
|
-
* `AbracadabraClient` + `AbracadabraProvider` directly — not through this
|
|
98
|
-
* façade. ChatClient handles only the *write-and-validate* path (sends,
|
|
99
|
-
* edits, deletes, typing, mark-read), where the server is the sole authority
|
|
100
|
-
* over the channel-period Y.Array.
|
|
101
|
-
*
|
|
102
|
-
* Events emitted:
|
|
103
|
-
* - `typing` → ChatTypingEvent (typing broadcast on the channel doc)
|
|
104
|
-
*
|
|
105
|
-
* For incoming-message observation, the consumer opens an
|
|
106
|
-
* `AbracadabraProvider` on the active period doc and observes its
|
|
107
|
-
* `messages` Y.Array directly. The dashboard's `useChat` composable does
|
|
108
|
-
* this; the integration tests do this; external consumers should mirror
|
|
109
|
-
* the pattern.
|
|
110
|
-
*/
|
|
111
|
-
export class ChatClient extends EventEmitter {
|
|
112
|
-
private readonly provider: ChatClientTransport;
|
|
113
|
-
private readonly responseTimeoutMs: number;
|
|
114
|
-
|
|
115
|
-
// FIFO of promises waiting on a typed `messages:ok` reply (keyed by source).
|
|
116
|
-
private readonly pending: Map<string, PendingResolver<any>[]> = new Map();
|
|
117
|
-
|
|
118
|
-
private readonly boundOnStateless: (data: { payload: string }) => void;
|
|
119
|
-
private readonly boundOnServerError: (data: {
|
|
120
|
-
source: string;
|
|
121
|
-
code: string;
|
|
122
|
-
message: string;
|
|
123
|
-
meta?: unknown;
|
|
124
|
-
}) => void;
|
|
125
|
-
|
|
126
|
-
constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {
|
|
127
|
-
super();
|
|
128
|
-
this.provider = provider;
|
|
129
|
-
this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
130
|
-
this.boundOnStateless = (data) => this.handleStateless(data.payload);
|
|
131
|
-
this.boundOnServerError = (data) => this.handleServerError(data);
|
|
132
|
-
this.provider.on("stateless", this.boundOnStateless);
|
|
133
|
-
// BaseProvider intercepts `{type:"error",source,code}` frames and emits
|
|
134
|
-
// them as `serverError`, not `stateless` — so request/response code paths
|
|
135
|
-
// must listen here to learn about rejections.
|
|
136
|
-
this.provider.on("serverError", this.boundOnServerError);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
destroy(): void {
|
|
140
|
-
this.provider.off("stateless", this.boundOnStateless);
|
|
141
|
-
this.provider.off("serverError", this.boundOnServerError);
|
|
142
|
-
for (const queue of this.pending.values()) {
|
|
143
|
-
for (const p of queue) {
|
|
144
|
-
clearTimeout(p.timer);
|
|
145
|
-
p.reject(new Error("ChatClient destroyed"));
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
this.pending.clear();
|
|
149
|
-
this.removeAllListeners();
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// ── Outgoing requests ──────────────────────────────────────────────────────
|
|
153
|
-
|
|
154
|
-
/** Send a chat message. Resolves with the server-assigned id, ts, and signatures. */
|
|
155
|
-
send(input: SendMessageInput): Promise<SendMessageResult> {
|
|
156
|
-
const promise = this.enqueue<SendMessageResult>("messages:send");
|
|
157
|
-
this.provider.sendStateless(
|
|
158
|
-
JSON.stringify({
|
|
159
|
-
type: "messages:send",
|
|
160
|
-
channel_doc_id: input.channel_doc_id,
|
|
161
|
-
content: input.content,
|
|
162
|
-
mentions: input.mentions ?? [],
|
|
163
|
-
...(input.reply_to !== undefined ? { reply_to: input.reply_to } : {}),
|
|
164
|
-
...(input.sig !== undefined ? { sig: input.sig } : {}),
|
|
165
|
-
...(input.ts_hint !== undefined ? { ts_hint: input.ts_hint } : {}),
|
|
166
|
-
}),
|
|
167
|
-
);
|
|
168
|
-
return promise;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/** Edit a previously-sent message. Append-only — server records an `edit` entry. */
|
|
172
|
-
edit(input: EditMessageInput): Promise<void> {
|
|
173
|
-
const promise = this.enqueue<void>("messages:edit");
|
|
174
|
-
this.provider.sendStateless(
|
|
175
|
-
JSON.stringify({
|
|
176
|
-
type: "messages:edit",
|
|
177
|
-
channel_doc_id: input.channel_doc_id,
|
|
178
|
-
message_id: input.message_id,
|
|
179
|
-
content: input.content,
|
|
180
|
-
...(input.sig !== undefined ? { sig: input.sig } : {}),
|
|
181
|
-
}),
|
|
182
|
-
);
|
|
183
|
-
return promise;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** Delete a message. Append-only — server records a `tombstone` entry. */
|
|
187
|
-
delete(input: DeleteMessageInput): Promise<void> {
|
|
188
|
-
const promise = this.enqueue<void>("messages:delete");
|
|
189
|
-
this.provider.sendStateless(
|
|
190
|
-
JSON.stringify({
|
|
191
|
-
type: "messages:delete",
|
|
192
|
-
channel_doc_id: input.channel_doc_id,
|
|
193
|
-
message_id: input.message_id,
|
|
194
|
-
}),
|
|
195
|
-
);
|
|
196
|
-
return promise;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Broadcast a typing indicator on a channel. Fire-and-forget. */
|
|
200
|
-
typing(channel_doc_id: string): void {
|
|
201
|
-
this.provider.sendStateless(
|
|
202
|
-
JSON.stringify({ type: "messages:typing", channel_doc_id }),
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/** Mark a (period, message) position as read for the calling user. Fire-and-forget. */
|
|
207
|
-
markRead(input: MarkReadInput): void {
|
|
208
|
-
this.provider.sendStateless(
|
|
209
|
-
JSON.stringify({
|
|
210
|
-
type: "messages:mark_read",
|
|
211
|
-
channel_doc_id: input.channel_doc_id,
|
|
212
|
-
period_id: input.period_id,
|
|
213
|
-
message_id: input.message_id,
|
|
214
|
-
...(input.ts !== undefined ? { ts: input.ts } : {}),
|
|
215
|
-
}),
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// ── Typed event subscription helpers ──────────────────────────────────────
|
|
220
|
-
|
|
221
|
-
/** Observe typing broadcasts. */
|
|
222
|
-
onTyping(fn: (e: ChatTypingEvent) => void): this {
|
|
223
|
-
return this.on("typing", fn) as this;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// ── Internals ─────────────────────────────────────────────────────────────
|
|
227
|
-
|
|
228
|
-
private enqueue<T>(source: string): Promise<T> {
|
|
229
|
-
return new Promise<T>((resolve, reject) => {
|
|
230
|
-
const timer = setTimeout(() => {
|
|
231
|
-
this.removePending(source, entry);
|
|
232
|
-
reject(new Error(`ChatClient: timeout waiting for ${source} ack`));
|
|
233
|
-
}, this.responseTimeoutMs);
|
|
234
|
-
const entry: PendingResolver<T> = { resolve, reject, timer };
|
|
235
|
-
const queue = this.pending.get(source) ?? [];
|
|
236
|
-
queue.push(entry);
|
|
237
|
-
this.pending.set(source, queue);
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
private removePending(source: string, entry: PendingResolver<any>): void {
|
|
242
|
-
const queue = this.pending.get(source);
|
|
243
|
-
if (!queue) return;
|
|
244
|
-
const idx = queue.indexOf(entry);
|
|
245
|
-
if (idx >= 0) queue.splice(idx, 1);
|
|
246
|
-
if (queue.length === 0) this.pending.delete(source);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
private resolveNext<T>(source: string, value: T): boolean {
|
|
250
|
-
const queue = this.pending.get(source);
|
|
251
|
-
if (!queue || queue.length === 0) return false;
|
|
252
|
-
const next = queue.shift()!;
|
|
253
|
-
if (queue.length === 0) this.pending.delete(source);
|
|
254
|
-
clearTimeout(next.timer);
|
|
255
|
-
next.resolve(value);
|
|
256
|
-
return true;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
private rejectNext(source: string, err: Error): boolean {
|
|
260
|
-
const queue = this.pending.get(source);
|
|
261
|
-
if (!queue || queue.length === 0) return false;
|
|
262
|
-
const next = queue.shift()!;
|
|
263
|
-
if (queue.length === 0) this.pending.delete(source);
|
|
264
|
-
clearTimeout(next.timer);
|
|
265
|
-
next.reject(err);
|
|
266
|
-
return true;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
private handleStateless(payload: string): void {
|
|
270
|
-
let parsed: any;
|
|
271
|
-
try {
|
|
272
|
-
parsed = JSON.parse(payload);
|
|
273
|
-
} catch {
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
const type: unknown = parsed?.type;
|
|
277
|
-
if (typeof type !== "string") return;
|
|
278
|
-
|
|
279
|
-
// Server emits `messages:ok` acks with a `source` matching the originating
|
|
280
|
-
// request type. Use that to resolve the matching pending promise.
|
|
281
|
-
if (type === "messages:ok" && typeof parsed.source === "string") {
|
|
282
|
-
this.resolveNext(parsed.source, parsed.meta);
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
if (type === "messages:typing") {
|
|
286
|
-
// The server includes channel_doc_id + user_id; the legacy
|
|
287
|
-
// ChatTypingEvent shape has `channel`, so emit it as the new doc id —
|
|
288
|
-
// consumers that want the old `group:<id>` form can prefix locally.
|
|
289
|
-
this.emit("typing", {
|
|
290
|
-
channel: parsed.channel_doc_id,
|
|
291
|
-
sender_id: parsed.user_id,
|
|
292
|
-
sender_name: null,
|
|
293
|
-
} as ChatTypingEvent);
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
private handleServerError(data: {
|
|
299
|
-
source: string;
|
|
300
|
-
code: string;
|
|
301
|
-
message: string;
|
|
302
|
-
meta?: unknown;
|
|
303
|
-
}): void {
|
|
304
|
-
if (typeof data.source !== "string" || !data.source.startsWith("messages:")) return;
|
|
305
|
-
if (data.source === "messages:inbox_fetch" || data.source === "messages:inbox_mark_read") {
|
|
306
|
-
// Inbox traffic belongs to NotificationsClient — let it handle its own errors.
|
|
307
|
-
return;
|
|
308
|
-
}
|
|
309
|
-
this.rejectNext(
|
|
310
|
-
data.source,
|
|
311
|
-
new Error(`${data.code ?? "error"}: ${data.message ?? "messages request failed"}`),
|
|
312
|
-
);
|
|
313
|
-
}
|
|
314
|
-
}
|
package/src/CloseEvents.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
export interface CloseEvent {
|
|
2
|
-
code: number;
|
|
3
|
-
reason: string;
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* The server is terminating the connection because a data frame was received
|
|
8
|
-
* that is too large.
|
|
9
|
-
* See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
|
|
10
|
-
*/
|
|
11
|
-
export const MessageTooBig: CloseEvent = {
|
|
12
|
-
code: 1009,
|
|
13
|
-
reason: "Message Too Big",
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* The server successfully processed the request, asks that the requester reset
|
|
18
|
-
* its document view, and is not returning any content.
|
|
19
|
-
*/
|
|
20
|
-
export const ResetConnection: CloseEvent = {
|
|
21
|
-
code: 4205,
|
|
22
|
-
reason: "Reset Connection",
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Similar to Forbidden, but specifically for use when authentication is required and has
|
|
27
|
-
* failed or has not yet been provided.
|
|
28
|
-
*/
|
|
29
|
-
export const Unauthorized: CloseEvent = {
|
|
30
|
-
code: 4401,
|
|
31
|
-
reason: "Unauthorized",
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* The request contained valid data and was understood by the server, but the server
|
|
36
|
-
* is refusing action.
|
|
37
|
-
*/
|
|
38
|
-
export const Forbidden: CloseEvent = {
|
|
39
|
-
code: 4403,
|
|
40
|
-
reason: "Forbidden",
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* The server timed out waiting for the request.
|
|
45
|
-
*/
|
|
46
|
-
export const ConnectionTimeout: CloseEvent = {
|
|
47
|
-
code: 4408,
|
|
48
|
-
reason: "Connection Timeout",
|
|
49
|
-
};
|