@practicalworks/rc-client 0.0.0-stage → 0.1.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/README.md +49 -2
- package/dist/client.d.ts +249 -0
- package/dist/client.js +487 -0
- package/dist/deadline.d.ts +12 -0
- package/dist/deadline.js +31 -0
- package/dist/errors.d.ts +50 -0
- package/dist/errors.js +66 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/payload.d.ts +63 -0
- package/dist/payload.js +112 -0
- package/dist/rate.d.ts +13 -0
- package/dist/rate.js +29 -0
- package/dist/split.d.ts +25 -0
- package/dist/split.js +78 -0
- package/dist/targets.d.ts +22 -0
- package/dist/targets.js +31 -0
- package/package.json +45 -4
package/dist/client.js
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import { fetchWithTimeout } from "./deadline.js";
|
|
2
|
+
import { namesUnknownRoom, parseErrorBody, RocketChatApiError, RocketChatPostError, } from "./errors.js";
|
|
3
|
+
import { fallbackCall, postCall, reactCall, roomIdOfCall, voiceFields } from "./payload.js";
|
|
4
|
+
import { withinRate } from "./rate.js";
|
|
5
|
+
import { RC_MAX_MESSAGE_CHARS, splitForRc } from "./split.js";
|
|
6
|
+
import { normalizeChannel } from "./targets.js";
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
8
|
+
const errorText = (err) => err?.message ?? String(err);
|
|
9
|
+
/**
|
|
10
|
+
* One Rocket.Chat REST client, in two registers:
|
|
11
|
+
*
|
|
12
|
+
* - **Delivering** (`postToChannel`, `postToRoom`, `postAsMember`, `uploadToRoom`,
|
|
13
|
+
* `getMessage`): posts as the bot and THROWS on failure. For a scheduled job or
|
|
14
|
+
* a tool call, a message that silently vanished is worse than an error.
|
|
15
|
+
* - **Replying** (`postReply`, `applyReactions`, `post`): posts as the room's
|
|
16
|
+
* identity and NEVER throws. For a live conversation, a failed post is logged
|
|
17
|
+
* and the conversation carries on.
|
|
18
|
+
*
|
|
19
|
+
* Room type (`isDirectMessage`), auth status and the reaction toggle (`react`)
|
|
20
|
+
* serve both.
|
|
21
|
+
*/
|
|
22
|
+
export class RocketChatClient {
|
|
23
|
+
baseUrl;
|
|
24
|
+
userId;
|
|
25
|
+
authToken;
|
|
26
|
+
timeoutMs;
|
|
27
|
+
maxMessageChars;
|
|
28
|
+
config;
|
|
29
|
+
fetchImpl;
|
|
30
|
+
log;
|
|
31
|
+
roomTypes = new Map();
|
|
32
|
+
/** `fetchImpl` is injectable for tests. */
|
|
33
|
+
constructor(config, fetchImpl = fetch) {
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
36
|
+
this.userId = config.userId;
|
|
37
|
+
this.authToken = config.authToken;
|
|
38
|
+
this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
39
|
+
this.maxMessageChars = config.maxMessageChars ?? RC_MAX_MESSAGE_CHARS;
|
|
40
|
+
this.fetchImpl = fetchImpl;
|
|
41
|
+
this.log = config.log ?? (() => { });
|
|
42
|
+
}
|
|
43
|
+
/** The bot's own user id, so a caller can tell its posts from a human's. */
|
|
44
|
+
get botUserId() {
|
|
45
|
+
return this.userId;
|
|
46
|
+
}
|
|
47
|
+
/** The bot's own auth headers; `json` adds the content-type a POST needs. The
|
|
48
|
+
* one place the credentials become headers. */
|
|
49
|
+
botHeaders(json = true) {
|
|
50
|
+
return {
|
|
51
|
+
...(json ? { "content-type": "application/json" } : {}),
|
|
52
|
+
"X-Auth-Token": this.authToken,
|
|
53
|
+
"X-User-Id": this.userId,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Auth for one call into a room. The identity is a property of the ROOM, not
|
|
57
|
+
* the call site, so an acknowledgement, the answer and a follow-up minutes later
|
|
58
|
+
* share one voice. Falls back to the bot's own credentials. */
|
|
59
|
+
async headersForRoom(roomId) {
|
|
60
|
+
if (!roomId || !this.config.identityForRoom)
|
|
61
|
+
return this.botHeaders();
|
|
62
|
+
try {
|
|
63
|
+
return (await this.config.identityForRoom(roomId)) ?? this.botHeaders();
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
this.log(`identity headers for ${roomId} failed: ${errorText(err)}`);
|
|
67
|
+
return this.botHeaders();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** A GET with this client's deadline, for reads the client has no method for
|
|
71
|
+
* (an attachment, a history page). The caller picks the headers. */
|
|
72
|
+
get(url, headers, label) {
|
|
73
|
+
return fetchWithTimeout(url, { headers }, label, this.timeoutMs, this.fetchImpl);
|
|
74
|
+
}
|
|
75
|
+
/** Check the bot credential (`/api/v1/me`) without exposing it. Never throws. */
|
|
76
|
+
async authStatus() {
|
|
77
|
+
try {
|
|
78
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/me`, { headers: this.botHeaders(false) }, "Rocket.Chat /api/v1/me", this.timeoutMs, this.fetchImpl);
|
|
79
|
+
if (res.ok)
|
|
80
|
+
return { ok: true, status: res.status };
|
|
81
|
+
return { ok: false, status: res.status, error: `Rocket.Chat /api/v1/me answered ${res.status}` };
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
return { ok: false, status: 0, error: errorText(err) };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// Delivering: as the bot, throws on failure.
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
/**
|
|
91
|
+
* Post BY NAME, so a caller never has to resolve an opaque room id first.
|
|
92
|
+
* Rocket.Chat's `channel` field takes `#name` for a channel and `@name` for a
|
|
93
|
+
* direct message, and opens the DM room if it does not exist yet, which is what
|
|
94
|
+
* lets an unattended job reach a person who is not watching a channel.
|
|
95
|
+
*
|
|
96
|
+
* Over the size limit the text goes as several posts: the first finds the room,
|
|
97
|
+
* the rest follow it there by id, in order.
|
|
98
|
+
*/
|
|
99
|
+
async postToChannel(channel, text, voice) {
|
|
100
|
+
const normalized = normalizeChannel(channel);
|
|
101
|
+
const name = normalized.startsWith("@") ? normalized : `#${normalized}`;
|
|
102
|
+
const extras = voiceFields(voice);
|
|
103
|
+
const [first = "", ...rest] = splitForRc(text, this.maxMessageChars);
|
|
104
|
+
let posted;
|
|
105
|
+
try {
|
|
106
|
+
const sent = await this.send({ channel: name, text: first, ...extras }, name);
|
|
107
|
+
posted = { messageId: sent.messageId, channel: name, ...(sent.roomId ? { roomId: sent.roomId } : {}) };
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
// A DM has no display name to fall back to, and an unknown @person is a
|
|
111
|
+
// real error rather than a lookup problem.
|
|
112
|
+
if (normalized.startsWith("@") || !isUnknownRoom(err))
|
|
113
|
+
throw err;
|
|
114
|
+
const roomId = await this.resolveByDisplayName(normalized);
|
|
115
|
+
if (!roomId)
|
|
116
|
+
throw err;
|
|
117
|
+
return this.postToRoom(roomId, text, undefined, voice);
|
|
118
|
+
}
|
|
119
|
+
for (const part of rest) {
|
|
120
|
+
await this.send(posted.roomId ? { roomId: posted.roomId, text: part, ...extras } : { channel: name, text: part, ...extras }, name);
|
|
121
|
+
}
|
|
122
|
+
return posted;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Find a room by its DISPLAY name, because a Rocket.Chat discussion does not
|
|
126
|
+
* answer to the name a human knows it by.
|
|
127
|
+
*
|
|
128
|
+
* A discussion's `name` is generated (a random mixed-case id), and the title
|
|
129
|
+
* everyone reads lives in `fname`. `chat.postMessage` resolves its `channel`
|
|
130
|
+
* field against `name` and never against `fname`, so a post to a discussion by
|
|
131
|
+
* its title fails with `[invalid-channel]` while the room is plainly visible.
|
|
132
|
+
* Matching on `fname` lets callers keep using the only spelling a human knows,
|
|
133
|
+
* even after case-folding.
|
|
134
|
+
*
|
|
135
|
+
* `rooms.get` returns the rooms this bot is SUBSCRIBED to, which needs no admin
|
|
136
|
+
* permission and includes discussions. That is also the honest limit: a room the
|
|
137
|
+
* bot has not joined is invisible here, and the caller gets the original
|
|
138
|
+
* `[invalid-channel]`, because "not a member" is what actually needs fixing.
|
|
139
|
+
*
|
|
140
|
+
* Not cached: this path only runs after a post has already failed, so it is
|
|
141
|
+
* rare, and a stale cached id would fail in a way that looks nothing like its
|
|
142
|
+
* cause.
|
|
143
|
+
*/
|
|
144
|
+
async resolveByDisplayName(displayName) {
|
|
145
|
+
let res;
|
|
146
|
+
try {
|
|
147
|
+
res = await fetchWithTimeout(`${this.baseUrl}/api/v1/rooms.get`, { headers: this.botHeaders(false) }, "Rocket.Chat rooms.get", this.timeoutMs, this.fetchImpl);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
if (!res.ok)
|
|
153
|
+
return undefined;
|
|
154
|
+
const body = (await res.json().catch(() => undefined));
|
|
155
|
+
const wanted = displayName.toLowerCase();
|
|
156
|
+
const hits = (body?.update ?? []).filter((room) => (room.fname ?? "").toLowerCase() === wanted && room._id);
|
|
157
|
+
// Two rooms sharing a display name is not a coin toss. A message delivered
|
|
158
|
+
// to the wrong room cannot be taken back, so an ambiguous lookup refuses.
|
|
159
|
+
if (hits.length > 1) {
|
|
160
|
+
const names = hits.map((r) => r.name ?? r._id).join(", ");
|
|
161
|
+
throw new Error(`Rocket.Chat has ${hits.length} rooms displayed as "${displayName}" (${names}). ` +
|
|
162
|
+
"Refusing to guess which one to post in — rename one, or route by its room id.");
|
|
163
|
+
}
|
|
164
|
+
return hits[0]?._id;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Post into a specific room, and optionally INSIDE a thread.
|
|
168
|
+
*
|
|
169
|
+
* `postToChannel` cannot do this: `channel` addresses a room by name, and a
|
|
170
|
+
* thread is not a name. It is the id of the message the thread hangs off, which
|
|
171
|
+
* only rides alongside a `roomId`. A missing `tmid` posts to the room root.
|
|
172
|
+
* Every part of an oversized text lands in the same room and thread.
|
|
173
|
+
*/
|
|
174
|
+
async postToRoom(roomId, text, tmid, voice) {
|
|
175
|
+
const label = tmid ? `room ${roomId} (thread ${tmid})` : `room ${roomId}`;
|
|
176
|
+
const extras = voiceFields(voice);
|
|
177
|
+
const body = (part) => tmid ? { roomId, text: part, tmid, ...extras } : { roomId, text: part, ...extras };
|
|
178
|
+
const [first = "", ...rest] = splitForRc(text, this.maxMessageChars);
|
|
179
|
+
const posted = await this.send(body(first), label);
|
|
180
|
+
for (const part of rest)
|
|
181
|
+
await this.send(body(part), label);
|
|
182
|
+
return { messageId: posted.messageId, channel: roomId, ...(posted.roomId ? { roomId: posted.roomId } : {}) };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Post as a subscribed member (`chat.sendMessage`). When Rocket.Chat answers
|
|
186
|
+
* `error-not-allowed` (a public channel the bot never joined), join it and try
|
|
187
|
+
* again, and if that is still refused, fall back to `chat.postMessage`, which
|
|
188
|
+
* needs no subscription.
|
|
189
|
+
*/
|
|
190
|
+
async postAsMember(roomId, text, opts) {
|
|
191
|
+
const message = {
|
|
192
|
+
rid: roomId,
|
|
193
|
+
msg: text,
|
|
194
|
+
...(opts?.tmid ? { tmid: opts.tmid } : {}),
|
|
195
|
+
...voiceFields(opts?.voice),
|
|
196
|
+
};
|
|
197
|
+
const label = opts?.tmid ? `room ${roomId} (thread ${opts.tmid})` : `room ${roomId}`;
|
|
198
|
+
const sendOnce = async () => {
|
|
199
|
+
const answer = (await this.call("chat.sendMessage", { body: JSON.stringify({ message }), json: true }, label));
|
|
200
|
+
return {
|
|
201
|
+
messageId: answer.message?._id ?? "",
|
|
202
|
+
channel: roomId,
|
|
203
|
+
...(answer.message?.rid ? { roomId: answer.message.rid } : { roomId }),
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
try {
|
|
207
|
+
return await sendOnce();
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
if (!isNotAllowed(err))
|
|
211
|
+
throw err;
|
|
212
|
+
if (await this.joinRoom(roomId)) {
|
|
213
|
+
try {
|
|
214
|
+
return await sendOnce();
|
|
215
|
+
}
|
|
216
|
+
catch (retryErr) {
|
|
217
|
+
if (!isNotAllowed(retryErr))
|
|
218
|
+
throw retryErr;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return this.postToRoom(roomId, text, opts?.tmid, opts?.voice);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Upload a file into a room as its own message, with `caption` as its text.
|
|
226
|
+
* `rooms.upload` was removed in Rocket.Chat 7.0, so it is two calls:
|
|
227
|
+
* `rooms.media` stores the file, `rooms.mediaConfirm` posts it. Both take a
|
|
228
|
+
* room id.
|
|
229
|
+
*/
|
|
230
|
+
async uploadToRoom(roomId, file, caption) {
|
|
231
|
+
const label = `room ${roomId}`;
|
|
232
|
+
const form = new FormData();
|
|
233
|
+
form.append("file", new Blob([file.bytes], { type: file.contentType }), file.name);
|
|
234
|
+
const stored = (await this.call(`rooms.media/${encodeURIComponent(roomId)}`, { body: form }, label));
|
|
235
|
+
const fileId = stored.file?._id;
|
|
236
|
+
if (!fileId)
|
|
237
|
+
throw new Error(`Rocket.Chat rooms.media for ${label} returned no file id; nothing was posted.`);
|
|
238
|
+
const confirmed = (await this.call(`rooms.mediaConfirm/${encodeURIComponent(roomId)}/${encodeURIComponent(fileId)}`, { body: JSON.stringify(caption ? { msg: caption } : {}), json: true }, label));
|
|
239
|
+
return { messageId: confirmed.message?._id ?? "", channel: roomId, roomId };
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Read one message by id (`chat.getMessage`). Returns null when Rocket.Chat says
|
|
243
|
+
* the message does not exist or is not visible to the bot, so a caller can
|
|
244
|
+
* refuse with a named reason instead of catching. Other errors throw.
|
|
245
|
+
*/
|
|
246
|
+
async getMessage(msgId) {
|
|
247
|
+
try {
|
|
248
|
+
const answer = (await this.getJson(`chat.getMessage?msgId=${encodeURIComponent(msgId)}`, "chat.getMessage"));
|
|
249
|
+
return answer.message ?? null;
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
if (err instanceof RocketChatApiError && (err.status === 400 || err.status === 404))
|
|
253
|
+
return null;
|
|
254
|
+
throw err;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Add or remove a reaction as the bot. `chat.react` toggles when `shouldReact`
|
|
259
|
+
* is omitted; pass it to force add or remove. Never throws: the message already
|
|
260
|
+
* landed, and a missing reaction is visible, not silent.
|
|
261
|
+
*/
|
|
262
|
+
async react(messageId, emoji, shouldReact) {
|
|
263
|
+
const payload = { messageId, emoji };
|
|
264
|
+
if (typeof shouldReact === "boolean")
|
|
265
|
+
payload.shouldReact = shouldReact;
|
|
266
|
+
try {
|
|
267
|
+
await this.call("chat.react", { body: JSON.stringify(payload), json: true }, `message ${messageId}`);
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Best-effort by contract.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/** Join a public channel by room id. True on success, false when Rocket.Chat
|
|
274
|
+
* refuses (a private group or a DM, where `channels.join` does not apply).
|
|
275
|
+
* Never throws. */
|
|
276
|
+
async joinRoom(roomId) {
|
|
277
|
+
try {
|
|
278
|
+
await this.call("channels.join", { body: JSON.stringify({ roomId }), json: true }, `room ${roomId}`);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// ---------------------------------------------------------------------------
|
|
286
|
+
// Replying: as the room's identity, never throws.
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
/** POST a JSON body as the room's identity and pull the new message id out.
|
|
289
|
+
* `roomId` is for bodies that name no room (`chat.react`). Resolves with
|
|
290
|
+
* `ok: false` on a refusal; throws only on transport errors and the deadline. */
|
|
291
|
+
async post(endpoint, body, roomId) {
|
|
292
|
+
const headers = await this.headersForRoom(roomId ?? roomIdOfCall(body));
|
|
293
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/${endpoint}`, { method: "POST", headers, body: JSON.stringify(body) }, `Rocket.Chat ${endpoint}`, this.timeoutMs, this.fetchImpl);
|
|
294
|
+
if (!res.ok)
|
|
295
|
+
return { ok: false, detail: `${res.status} ${(await res.text()).slice(0, 300)}` };
|
|
296
|
+
const parsed = (await res.json());
|
|
297
|
+
return { ok: true, id: parsed.message?._id };
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Post one message that already fits. Never throws.
|
|
301
|
+
*
|
|
302
|
+
* Two endpoints, in this order: `tshow` is a field of chat.sendMessage's message
|
|
303
|
+
* object, and chat.postMessage 400s on it. So try chat.sendMessage when `tshow`
|
|
304
|
+
* is wanted and ALWAYS fall back to plain chat.postMessage: losing `tshow` is
|
|
305
|
+
* cosmetic, losing the reply is not. The payload shapes live in payload.ts.
|
|
306
|
+
*/
|
|
307
|
+
async postOne(roomId, text, tmid, voice) {
|
|
308
|
+
try {
|
|
309
|
+
const primary = postCall(roomId, text, tmid, this.config.threadShow ?? false, voice);
|
|
310
|
+
const sent = await this.post(primary.endpoint, primary.body);
|
|
311
|
+
if (sent.ok)
|
|
312
|
+
return sent.id;
|
|
313
|
+
if (primary.endpoint === "chat.postMessage") {
|
|
314
|
+
this.log(`postMessage to ${roomId} failed: ${sent.detail}`);
|
|
315
|
+
return undefined;
|
|
316
|
+
}
|
|
317
|
+
this.log(`${primary.endpoint} to ${roomId} failed: ${sent.detail} — falling back to chat.postMessage`);
|
|
318
|
+
const fallback = fallbackCall(roomId, text, tmid, voice);
|
|
319
|
+
const posted = await this.post(fallback.endpoint, fallback.body);
|
|
320
|
+
if (!posted.ok) {
|
|
321
|
+
this.log(`postMessage to ${roomId} failed: ${posted.detail}`);
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
return posted.id;
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
this.log(`postMessage to ${roomId} threw: ${errorText(err)}`);
|
|
328
|
+
return undefined;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Post a reply, split to fit the size limit. Parts go out in order into the
|
|
333
|
+
* same thread; returns the FIRST part's id, or undefined when it did not post.
|
|
334
|
+
* Never throws.
|
|
335
|
+
*
|
|
336
|
+
* The post cap sits here so no path can forget it. `uncapped` is for control
|
|
337
|
+
* replies only, so the cap can never take away the command that stops a loop.
|
|
338
|
+
* `outbound` runs BEFORE the split, so a voice applies to every part.
|
|
339
|
+
*/
|
|
340
|
+
async postReply(roomId, text, tmid, opts = {}) {
|
|
341
|
+
const cap = this.config.postCap;
|
|
342
|
+
if (cap && !opts.uncapped && !withinRate(cap.rate, `${roomId}:${tmid ?? "-"}`, Date.now(), cap.maxPosts, cap.windowMs)) {
|
|
343
|
+
this.log(`post cap hit for ${roomId}:${tmid ?? "-"} — dropping a message to break a loop`);
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
const { text: body, voice } = this.config.outbound ? this.config.outbound(text) : { text, voice: undefined };
|
|
347
|
+
const parts = splitForRc(body, this.maxMessageChars);
|
|
348
|
+
if (parts.length === 1)
|
|
349
|
+
return this.postOne(roomId, parts[0], tmid, voice);
|
|
350
|
+
this.log(`reply to ${roomId} is ${body.length} chars — posting as ${parts.length} messages`);
|
|
351
|
+
let firstId;
|
|
352
|
+
for (const [i, part] of parts.entries()) {
|
|
353
|
+
const id = await this.postOne(roomId, part, tmid, voice);
|
|
354
|
+
if (i === 0)
|
|
355
|
+
firstId = id;
|
|
356
|
+
// A partial answer beats a silent one: the remaining parts still go.
|
|
357
|
+
if (!id)
|
|
358
|
+
this.log(`part ${i + 1}/${parts.length} to ${roomId} did not post`);
|
|
359
|
+
}
|
|
360
|
+
return firstId;
|
|
361
|
+
}
|
|
362
|
+
/** Set or clear reactions as the room's identity, always stating
|
|
363
|
+
* `shouldReact`. Never throws: a reaction is a courtesy and must never cost the
|
|
364
|
+
* conversation it decorates. */
|
|
365
|
+
async applyReactions(roomId, messageId, changes) {
|
|
366
|
+
for (const change of changes) {
|
|
367
|
+
try {
|
|
368
|
+
const call = reactCall(messageId, change.emoji, change.shouldReact);
|
|
369
|
+
const res = await this.post(call.endpoint, call.body, roomId);
|
|
370
|
+
if (!res.ok)
|
|
371
|
+
this.log(`chat.react :${change.emoji}: on ${messageId} failed: ${res.detail}`);
|
|
372
|
+
}
|
|
373
|
+
catch (err) {
|
|
374
|
+
this.log(`chat.react :${change.emoji}: on ${messageId} threw: ${errorText(err)}`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
// Room type.
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
/**
|
|
382
|
+
* Is this room a direct message? Room ids are opaque, so the type comes from
|
|
383
|
+
* `rooms.info`, cached because a room's type is stable. A refusal is not an
|
|
384
|
+
* error: a DM the bot is not a member of refuses, so `isDirectMessageFallback`
|
|
385
|
+
* is asked. When the answer is uncertain this returns false and caches nothing,
|
|
386
|
+
* so the next call asks again.
|
|
387
|
+
*/
|
|
388
|
+
async isDirectMessage(roomId) {
|
|
389
|
+
const cached = this.roomTypes.get(roomId);
|
|
390
|
+
if (cached !== undefined)
|
|
391
|
+
return cached === "d";
|
|
392
|
+
try {
|
|
393
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/rooms.info?roomId=${encodeURIComponent(roomId)}`, { headers: this.botHeaders(false) }, "Rocket.Chat rooms.info", this.timeoutMs, this.fetchImpl);
|
|
394
|
+
if (res.ok) {
|
|
395
|
+
const type = (await res.json()).room?.t ?? "";
|
|
396
|
+
this.roomTypes.set(roomId, type);
|
|
397
|
+
return type === "d";
|
|
398
|
+
}
|
|
399
|
+
if (this.config.isDirectMessageFallback && (await this.config.isDirectMessageFallback(roomId))) {
|
|
400
|
+
this.roomTypes.set(roomId, "d");
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
this.log(`rooms.info ${roomId} failed: ${res.status}`);
|
|
404
|
+
}
|
|
405
|
+
catch (err) {
|
|
406
|
+
this.log(`rooms.info ${roomId} threw: ${errorText(err)}`);
|
|
407
|
+
}
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
/** The type `isDirectMessage` learned (`c`, `p`, `d`, …); never a call of its own. */
|
|
411
|
+
cachedRoomType(roomId) {
|
|
412
|
+
return this.roomTypes.get(roomId);
|
|
413
|
+
}
|
|
414
|
+
// ---------------------------------------------------------------------------
|
|
415
|
+
// Transport.
|
|
416
|
+
// ---------------------------------------------------------------------------
|
|
417
|
+
/** A GET to the REST API that throws a typed error on a non-2xx. */
|
|
418
|
+
async getJson(path, endpoint) {
|
|
419
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/${path}`, { headers: this.botHeaders(false) }, `Rocket.Chat ${endpoint}`, this.timeoutMs, this.fetchImpl);
|
|
420
|
+
if (!res.ok) {
|
|
421
|
+
const text = await res.text();
|
|
422
|
+
throw new RocketChatApiError(res.status, endpoint, parseErrorBody(text)?.error, text);
|
|
423
|
+
}
|
|
424
|
+
return res.json();
|
|
425
|
+
}
|
|
426
|
+
/** A POST to the REST API as the bot that throws on a non-2xx and on
|
|
427
|
+
* Rocket.Chat's `success: false`. */
|
|
428
|
+
async call(path, init, _label) {
|
|
429
|
+
const route = path.split("/")[0] ?? path;
|
|
430
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/${path}`, { method: "POST", headers: this.botHeaders(init.json ?? false), body: init.body }, `Rocket.Chat ${route}`, this.timeoutMs, this.fetchImpl);
|
|
431
|
+
if (!res.ok) {
|
|
432
|
+
const text = await res.text();
|
|
433
|
+
throw new RocketChatApiError(res.status, route, parseErrorBody(text)?.error, text);
|
|
434
|
+
}
|
|
435
|
+
const answer = (await res.json());
|
|
436
|
+
if (answer.success === false) {
|
|
437
|
+
throw new RocketChatApiError(200, route, answer.error, answer.error ?? "unknown error");
|
|
438
|
+
}
|
|
439
|
+
return answer;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* The delivering `chat.postMessage`, and every way it can fail to deliver.
|
|
443
|
+
* `label` names the target back to a caller who has to fix it; it never appears
|
|
444
|
+
* in the request.
|
|
445
|
+
*/
|
|
446
|
+
async send(body, label) {
|
|
447
|
+
const res = await fetchWithTimeout(`${this.baseUrl}/api/v1/chat.postMessage`, { method: "POST", headers: this.botHeaders(), body: JSON.stringify(body) }, "Rocket.Chat chat.postMessage", this.timeoutMs, this.fetchImpl);
|
|
448
|
+
if (!res.ok) {
|
|
449
|
+
const text = await res.text();
|
|
450
|
+
const parsed = parseErrorBody(text);
|
|
451
|
+
// A 400 is how Rocket.Chat answers "no such room". A 401, a 403 or a 5xx
|
|
452
|
+
// that happens to quote the same token is an auth or availability failure
|
|
453
|
+
// and must stay reportable as itself, so the status gates the
|
|
454
|
+
// classification too.
|
|
455
|
+
throw new RocketChatPostError(`Rocket.Chat chat.postMessage to ${label} failed: ${res.status} ${text.slice(0, 300)}`, {
|
|
456
|
+
unknownRoom: res.status === 400 && namesUnknownRoom(parsed),
|
|
457
|
+
status: res.status,
|
|
458
|
+
rcError: parsed?.errorType ?? parsed?.error,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
// Rocket.Chat answers 200 with `success: false` for a channel the bot cannot
|
|
462
|
+
// see, so the status code alone is not proof of delivery.
|
|
463
|
+
const answer = (await res.json());
|
|
464
|
+
if (answer.success === false) {
|
|
465
|
+
throw new RocketChatPostError(`Rocket.Chat refused the post to ${label}: ${answer.error ?? "unknown error"}. ` +
|
|
466
|
+
"The bot may not be a member of that room.", { unknownRoom: namesUnknownRoom(answer), status: 200, rcError: answer.errorType ?? answer.error });
|
|
467
|
+
}
|
|
468
|
+
return {
|
|
469
|
+
messageId: answer.message?._id ?? "",
|
|
470
|
+
...(answer.message?.rid ? { roomId: answer.message.rid } : {}),
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* May this failure be retried as a display-name lookup? Only a post Rocket.Chat
|
|
476
|
+
* itself classified as an unknown room. A timeout, a network error, a 401, a 403
|
|
477
|
+
* and a 5xx keep their identity and are rethrown: retried down the lookup path,
|
|
478
|
+
* they could surface as an unrelated ambiguous-room error, or deliver by id a
|
|
479
|
+
* message the first failure should have stopped.
|
|
480
|
+
*/
|
|
481
|
+
function isUnknownRoom(err) {
|
|
482
|
+
return err instanceof RocketChatPostError && err.unknownRoom;
|
|
483
|
+
}
|
|
484
|
+
/** Rocket.Chat refused because the bot is not a member of the room. */
|
|
485
|
+
function isNotAllowed(err) {
|
|
486
|
+
return err instanceof RocketChatApiError && err.rcError === "error-not-allowed";
|
|
487
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The deadline passed before the response headers arrived. Typed so a caller
|
|
2
|
+
* classifies a timeout by what it is, never by matching the message text. */
|
|
3
|
+
export declare class DeadlineError extends Error {
|
|
4
|
+
readonly label: string;
|
|
5
|
+
readonly timeoutMs: number;
|
|
6
|
+
readonly code = "deadline";
|
|
7
|
+
constructor(label: string, timeoutMs: number);
|
|
8
|
+
}
|
|
9
|
+
/** fetch with a hard deadline. On timeout it throws a DeadlineError, because
|
|
10
|
+
* undici's raw AbortError only says "This operation was aborted". A transport
|
|
11
|
+
* error that is not the deadline passes through as it is. */
|
|
12
|
+
export declare function fetchWithTimeout(url: string, init: RequestInit, label: string, timeoutMs: number, fetchImpl?: typeof fetch): Promise<Response>;
|
package/dist/deadline.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The deadline passed before the response headers arrived. Typed so a caller
|
|
2
|
+
* classifies a timeout by what it is, never by matching the message text. */
|
|
3
|
+
export class DeadlineError extends Error {
|
|
4
|
+
label;
|
|
5
|
+
timeoutMs;
|
|
6
|
+
code = "deadline";
|
|
7
|
+
constructor(label, timeoutMs) {
|
|
8
|
+
super(`${label} timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
9
|
+
this.label = label;
|
|
10
|
+
this.timeoutMs = timeoutMs;
|
|
11
|
+
this.name = "DeadlineError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** fetch with a hard deadline. On timeout it throws a DeadlineError, because
|
|
15
|
+
* undici's raw AbortError only says "This operation was aborted". A transport
|
|
16
|
+
* error that is not the deadline passes through as it is. */
|
|
17
|
+
export async function fetchWithTimeout(url, init, label, timeoutMs, fetchImpl = fetch) {
|
|
18
|
+
const ctrl = new AbortController();
|
|
19
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
20
|
+
try {
|
|
21
|
+
return await fetchImpl(url, { ...init, signal: ctrl.signal });
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
if (ctrl.signal.aborted)
|
|
25
|
+
throw new DeadlineError(label, timeoutMs);
|
|
26
|
+
throw err;
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
}
|
|
31
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Rocket.Chat REST failure with the HTTP status and Rocket.Chat's
|
|
3
|
+
* machine-readable `error` code as fields, so callers branch on the kind of
|
|
4
|
+
* failure instead of parsing the message string.
|
|
5
|
+
*/
|
|
6
|
+
export declare class RocketChatApiError extends Error {
|
|
7
|
+
readonly status: number;
|
|
8
|
+
readonly endpoint: string;
|
|
9
|
+
readonly rcError: string | undefined;
|
|
10
|
+
readonly body: string;
|
|
11
|
+
constructor(status: number, endpoint: string, rcError: string | undefined, body: string);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A post Rocket.Chat rejected, carrying WHY as a field rather than leaving it to
|
|
15
|
+
* be read back out of the message text. Only `unknownRoom` may trigger the
|
|
16
|
+
* display-name fallback, so it is precisely the fact that must not be forgeable
|
|
17
|
+
* by arbitrary server text quoted into the message.
|
|
18
|
+
*/
|
|
19
|
+
export declare class RocketChatPostError extends RocketChatApiError {
|
|
20
|
+
/** True only when Rocket.Chat itself classified the failure as "no such room". */
|
|
21
|
+
readonly unknownRoom: boolean;
|
|
22
|
+
constructor(message: string, options: {
|
|
23
|
+
unknownRoom: boolean;
|
|
24
|
+
status?: number;
|
|
25
|
+
rcError?: string;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** The JSON body Rocket.Chat returns when it refuses a call. */
|
|
29
|
+
export interface RocketChatErrorBody {
|
|
30
|
+
success?: boolean;
|
|
31
|
+
error?: string;
|
|
32
|
+
errorType?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Parse an error body WITHOUT trusting it to be JSON. A proxy in front of
|
|
36
|
+
* Rocket.Chat answers an outage with an HTML page, and an unguarded parse there
|
|
37
|
+
* throws a SyntaxError that buries the status worth reporting.
|
|
38
|
+
*/
|
|
39
|
+
export declare function parseErrorBody(text: string): RocketChatErrorBody | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Did Rocket.Chat's OWN error field name an unknown room?
|
|
42
|
+
*
|
|
43
|
+
* Read from the parsed `error`/`errorType` fields and compared WHOLE, never
|
|
44
|
+
* searched for inside a rendered message. The message embeds up to 300 characters
|
|
45
|
+
* of a server-controlled body, so a substring test over it is satisfied by any
|
|
46
|
+
* failure that merely quotes the token: a 401, a 403, or a proxy's HTML error
|
|
47
|
+
* page. Rocket.Chat brackets the value on some routes and not on others, so the
|
|
48
|
+
* brackets come off before the comparison.
|
|
49
|
+
*/
|
|
50
|
+
export declare function namesUnknownRoom(body: RocketChatErrorBody | undefined): boolean;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Rocket.Chat REST failure with the HTTP status and Rocket.Chat's
|
|
3
|
+
* machine-readable `error` code as fields, so callers branch on the kind of
|
|
4
|
+
* failure instead of parsing the message string.
|
|
5
|
+
*/
|
|
6
|
+
export class RocketChatApiError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
endpoint;
|
|
9
|
+
rcError;
|
|
10
|
+
body;
|
|
11
|
+
constructor(status, endpoint, rcError, body) {
|
|
12
|
+
super(`Rocket.Chat API error ${status} on ${endpoint}: ${body.slice(0, 300)}`);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.endpoint = endpoint;
|
|
15
|
+
this.rcError = rcError;
|
|
16
|
+
this.body = body;
|
|
17
|
+
this.name = "RocketChatApiError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A post Rocket.Chat rejected, carrying WHY as a field rather than leaving it to
|
|
22
|
+
* be read back out of the message text. Only `unknownRoom` may trigger the
|
|
23
|
+
* display-name fallback, so it is precisely the fact that must not be forgeable
|
|
24
|
+
* by arbitrary server text quoted into the message.
|
|
25
|
+
*/
|
|
26
|
+
export class RocketChatPostError extends RocketChatApiError {
|
|
27
|
+
/** True only when Rocket.Chat itself classified the failure as "no such room". */
|
|
28
|
+
unknownRoom;
|
|
29
|
+
constructor(message, options) {
|
|
30
|
+
super(options.status ?? 0, "chat.postMessage", options.rcError, message);
|
|
31
|
+
this.name = "RocketChatPostError";
|
|
32
|
+
this.message = message;
|
|
33
|
+
this.unknownRoom = options.unknownRoom;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Rocket.Chat's own names for "no such room", across the two error shapes it
|
|
37
|
+
* uses: a bracketed `error` on some routes, a typed `errorType` on others. */
|
|
38
|
+
const UNKNOWN_ROOM_ERRORS = new Set(["invalid-channel", "error-room-not-found"]);
|
|
39
|
+
/**
|
|
40
|
+
* Parse an error body WITHOUT trusting it to be JSON. A proxy in front of
|
|
41
|
+
* Rocket.Chat answers an outage with an HTML page, and an unguarded parse there
|
|
42
|
+
* throws a SyntaxError that buries the status worth reporting.
|
|
43
|
+
*/
|
|
44
|
+
export function parseErrorBody(text) {
|
|
45
|
+
try {
|
|
46
|
+
const parsed = JSON.parse(text);
|
|
47
|
+
return parsed !== null && typeof parsed === "object" ? parsed : undefined;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Did Rocket.Chat's OWN error field name an unknown room?
|
|
55
|
+
*
|
|
56
|
+
* Read from the parsed `error`/`errorType` fields and compared WHOLE, never
|
|
57
|
+
* searched for inside a rendered message. The message embeds up to 300 characters
|
|
58
|
+
* of a server-controlled body, so a substring test over it is satisfied by any
|
|
59
|
+
* failure that merely quotes the token: a 401, a 403, or a proxy's HTML error
|
|
60
|
+
* page. Rocket.Chat brackets the value on some routes and not on others, so the
|
|
61
|
+
* brackets come off before the comparison.
|
|
62
|
+
*/
|
|
63
|
+
export function namesUnknownRoom(body) {
|
|
64
|
+
return [body?.errorType, body?.error].some((value) => typeof value === "string" &&
|
|
65
|
+
UNKNOWN_ROOM_ERRORS.has(value.trim().replace(/^\[/, "").replace(/\]$/, "").toLowerCase()));
|
|
66
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { RocketChatClient, type PostedMessage, type RawPostResult, type RcHeaders, type RcLog, type ReactionChange, type RocketChatAuthStatus, type RocketChatConfig, type RocketChatMessage, type RoomFile, } from "./client.js";
|
|
2
|
+
export { RocketChatApiError, RocketChatPostError } from "./errors.js";
|
|
3
|
+
export { DeadlineError, fetchWithTimeout } from "./deadline.js";
|
|
4
|
+
export { fallbackCall, illegalPostKeys, illegalReactKeys, illegalSendMessageKeys, postCall, reactCall, roomIdOfCall, type PostVoice, type RcCall, } from "./payload.js";
|
|
5
|
+
export { DEFAULT_LOOP_WINDOW_MS, DEFAULT_MAX_POSTS_PER_THREAD, withinRate } from "./rate.js";
|
|
6
|
+
export { RC_MAX_MESSAGE_CHARS, RC_MAX_PARTS, splitForRc } from "./split.js";
|
|
7
|
+
export { isDirectTarget, normalizeChannel, normalizeTargets } from "./targets.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { RocketChatClient, } from "./client.js";
|
|
2
|
+
export { RocketChatApiError, RocketChatPostError } from "./errors.js";
|
|
3
|
+
export { DeadlineError, fetchWithTimeout } from "./deadline.js";
|
|
4
|
+
export { fallbackCall, illegalPostKeys, illegalReactKeys, illegalSendMessageKeys, postCall, reactCall, roomIdOfCall, } from "./payload.js";
|
|
5
|
+
export { DEFAULT_LOOP_WINDOW_MS, DEFAULT_MAX_POSTS_PER_THREAD, withinRate } from "./rate.js";
|
|
6
|
+
export { RC_MAX_MESSAGE_CHARS, RC_MAX_PARTS, splitForRc } from "./split.js";
|
|
7
|
+
export { isDirectTarget, normalizeChannel, normalizeTargets } from "./targets.js";
|