@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.
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Which Rocket.Chat endpoint a post goes to, and exactly what body it carries.
3
+ *
4
+ * Pure, so the shapes are unit-tested. `chat.postMessage` validates with
5
+ * `additionalProperties: false`, so ONE extra key turns the whole post into a 400:
6
+ *
7
+ * must NOT have additional properties
8
+ * must have required property 'channel'
9
+ * must match exactly one schema in oneOf
10
+ *
11
+ * "Also send to channel" is `tshow`, and it is a field of chat.sendMessage's
12
+ * `message` object, not a parameter of chat.postMessage. A fake server that
13
+ * accepts any JSON will not catch a mistake here; the real API will.
14
+ */
15
+ /** Optional voice on a post: a display name and avatar to post under instead of
16
+ * the bot's own. Omitted fields are left off the body entirely. */
17
+ export interface PostVoice {
18
+ alias?: string;
19
+ avatar?: string;
20
+ }
21
+ /** Only the fields Rocket.Chat should see. A blank value is omitted, not sent:
22
+ * Rocket.Chat treats an empty `avatar` as an override to nothing, which is worse
23
+ * than not overriding. */
24
+ export declare function voiceFields(voice: PostVoice | undefined): {
25
+ alias?: string;
26
+ avatar?: string;
27
+ };
28
+ export interface RcCall {
29
+ endpoint: "chat.postMessage" | "chat.sendMessage" | "chat.react";
30
+ body: Record<string, unknown>;
31
+ }
32
+ /**
33
+ * The call that posts `text` into `roomId`, in thread `tmid`.
34
+ *
35
+ * `chat.sendMessage` is used ONLY when `tshow` is actually wanted: a threaded
36
+ * reply with "also send to channel" on. Everything else takes plain
37
+ * `chat.postMessage`. `tshow` is never sent as `false`: an explicit `false` is
38
+ * still an extra property and still a 400, which would make turning the feature
39
+ * off break every post instead.
40
+ */
41
+ export declare function postCall(roomId: string, text: string, tmid: string | undefined, threadShow: boolean, voice?: PostVoice): RcCall;
42
+ /** The fallback call: plain `chat.postMessage`, which must always be accepted.
43
+ * Used when `chat.sendMessage` fails: losing "also send to channel" is cosmetic,
44
+ * losing the message is not. */
45
+ export declare function fallbackCall(roomId: string, text: string, tmid: string | undefined, voice?: PostVoice): RcCall;
46
+ /** Set (or clear) a reaction on a message. `emoji` is a shortcode NAME:
47
+ * Rocket.Chat refuses a raw Unicode character. `shouldReact` is always sent,
48
+ * which makes the call a setter: replaying it is harmless, where a bare toggle
49
+ * would flip a reaction back off. The body carries no room, so a caller that
50
+ * posts as a room's identity must name the room separately. */
51
+ export declare function reactCall(messageId: string, emoji: string, shouldReact: boolean): RcCall;
52
+ /** Keys in a `chat.react` body outside what this client means to send. Empty is
53
+ * the only acceptable answer. */
54
+ export declare function illegalReactKeys(body: Record<string, unknown>): string[];
55
+ /** Keys in a `chat.postMessage` body that the API would reject. Empty is the
56
+ * only acceptable answer. */
57
+ export declare function illegalPostKeys(body: Record<string, unknown>): string[];
58
+ /** Keys in a `chat.sendMessage` `message` object that the API would reject.
59
+ * Empty is the only acceptable answer. */
60
+ export declare function illegalSendMessageKeys(body: Record<string, unknown>): string[];
61
+ /** Which room a call posts into: `chat.postMessage` carries `roomId`,
62
+ * `chat.sendMessage` nests `message.rid`, `chat.react` names none. */
63
+ export declare function roomIdOfCall(body: unknown): string | undefined;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Which Rocket.Chat endpoint a post goes to, and exactly what body it carries.
3
+ *
4
+ * Pure, so the shapes are unit-tested. `chat.postMessage` validates with
5
+ * `additionalProperties: false`, so ONE extra key turns the whole post into a 400:
6
+ *
7
+ * must NOT have additional properties
8
+ * must have required property 'channel'
9
+ * must match exactly one schema in oneOf
10
+ *
11
+ * "Also send to channel" is `tshow`, and it is a field of chat.sendMessage's
12
+ * `message` object, not a parameter of chat.postMessage. A fake server that
13
+ * accepts any JSON will not catch a mistake here; the real API will.
14
+ */
15
+ /** The exact keys `chat.postMessage` accepts. Anything else is a 400, so this
16
+ * list is a hard contract, not documentation. */
17
+ const POST_MESSAGE_ALLOWED_KEYS = [
18
+ "roomId",
19
+ "channel",
20
+ "text",
21
+ "tmid",
22
+ "alias",
23
+ "emoji",
24
+ "avatar",
25
+ "attachments",
26
+ ];
27
+ /** The keys `chat.sendMessage`'s nested `message` object accepts. A second
28
+ * contract: this endpoint has its own schema, and a voice on a threaded reply
29
+ * goes inside `message` rather than beside it. */
30
+ const SEND_MESSAGE_MESSAGE_ALLOWED_KEYS = [
31
+ "rid",
32
+ "msg",
33
+ "tmid",
34
+ "tshow",
35
+ "alias",
36
+ "avatar",
37
+ "emoji",
38
+ "attachments",
39
+ ];
40
+ /** The keys `chat.react` accepts that this client ever sends. */
41
+ const REACT_ALLOWED_KEYS = ["messageId", "emoji", "shouldReact"];
42
+ /** Only the fields Rocket.Chat should see. A blank value is omitted, not sent:
43
+ * Rocket.Chat treats an empty `avatar` as an override to nothing, which is worse
44
+ * than not overriding. */
45
+ export function voiceFields(voice) {
46
+ if (!voice)
47
+ return {};
48
+ return {
49
+ ...(voice.alias ? { alias: voice.alias } : {}),
50
+ ...(voice.avatar ? { avatar: voice.avatar } : {}),
51
+ };
52
+ }
53
+ /**
54
+ * The call that posts `text` into `roomId`, in thread `tmid`.
55
+ *
56
+ * `chat.sendMessage` is used ONLY when `tshow` is actually wanted: a threaded
57
+ * reply with "also send to channel" on. Everything else takes plain
58
+ * `chat.postMessage`. `tshow` is never sent as `false`: an explicit `false` is
59
+ * still an extra property and still a 400, which would make turning the feature
60
+ * off break every post instead.
61
+ */
62
+ export function postCall(roomId, text, tmid, threadShow, voice) {
63
+ if (tmid && threadShow) {
64
+ return {
65
+ endpoint: "chat.sendMessage",
66
+ body: { message: { rid: roomId, msg: text, tmid, tshow: true, ...voiceFields(voice) } },
67
+ };
68
+ }
69
+ return {
70
+ endpoint: "chat.postMessage",
71
+ body: { roomId, text, ...(tmid ? { tmid } : {}), ...voiceFields(voice) },
72
+ };
73
+ }
74
+ /** The fallback call: plain `chat.postMessage`, which must always be accepted.
75
+ * Used when `chat.sendMessage` fails: losing "also send to channel" is cosmetic,
76
+ * losing the message is not. */
77
+ export function fallbackCall(roomId, text, tmid, voice) {
78
+ return {
79
+ endpoint: "chat.postMessage",
80
+ body: { roomId, text, ...(tmid ? { tmid } : {}), ...voiceFields(voice) },
81
+ };
82
+ }
83
+ /** Set (or clear) a reaction on a message. `emoji` is a shortcode NAME:
84
+ * Rocket.Chat refuses a raw Unicode character. `shouldReact` is always sent,
85
+ * which makes the call a setter: replaying it is harmless, where a bare toggle
86
+ * would flip a reaction back off. The body carries no room, so a caller that
87
+ * posts as a room's identity must name the room separately. */
88
+ export function reactCall(messageId, emoji, shouldReact) {
89
+ return { endpoint: "chat.react", body: { messageId, emoji, shouldReact } };
90
+ }
91
+ /** Keys in a `chat.react` body outside what this client means to send. Empty is
92
+ * the only acceptable answer. */
93
+ export function illegalReactKeys(body) {
94
+ return Object.keys(body).filter((k) => !REACT_ALLOWED_KEYS.includes(k));
95
+ }
96
+ /** Keys in a `chat.postMessage` body that the API would reject. Empty is the
97
+ * only acceptable answer. */
98
+ export function illegalPostKeys(body) {
99
+ return Object.keys(body).filter((k) => !POST_MESSAGE_ALLOWED_KEYS.includes(k));
100
+ }
101
+ /** Keys in a `chat.sendMessage` `message` object that the API would reject.
102
+ * Empty is the only acceptable answer. */
103
+ export function illegalSendMessageKeys(body) {
104
+ const message = (body.message ?? {});
105
+ return Object.keys(message).filter((k) => !SEND_MESSAGE_MESSAGE_ALLOWED_KEYS.includes(k));
106
+ }
107
+ /** Which room a call posts into: `chat.postMessage` carries `roomId`,
108
+ * `chat.sendMessage` nests `message.rid`, `chat.react` names none. */
109
+ export function roomIdOfCall(body) {
110
+ const b = body;
111
+ return b?.roomId ?? b?.message?.rid;
112
+ }
package/dist/rate.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The post cap: a sliding-window counter per key (a room and thread), so a loop
3
+ * between two bots cannot flood a room. It counts what the client sends, and
4
+ * nothing about how much a person may say.
5
+ */
6
+ /** Window and ceiling a caller can start from: 40 posts per thread per 10 minutes. */
7
+ export declare const DEFAULT_LOOP_WINDOW_MS: number;
8
+ export declare const DEFAULT_MAX_POSTS_PER_THREAD = 40;
9
+ /** How many keys the counter keeps before it drops the oldest. */
10
+ export declare const MAX_RATE_KEYS = 200;
11
+ /** Returns false once `max` events have happened inside `windowMs`, and prunes as
12
+ * it goes so the map cannot grow forever. */
13
+ export declare function withinRate(seen: Map<string, number[]>, key: string, now: number, max: number, windowMs: number): boolean;
package/dist/rate.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The post cap: a sliding-window counter per key (a room and thread), so a loop
3
+ * between two bots cannot flood a room. It counts what the client sends, and
4
+ * nothing about how much a person may say.
5
+ */
6
+ /** Window and ceiling a caller can start from: 40 posts per thread per 10 minutes. */
7
+ export const DEFAULT_LOOP_WINDOW_MS = 10 * 60_000;
8
+ export const DEFAULT_MAX_POSTS_PER_THREAD = 40;
9
+ /** How many keys the counter keeps before it drops the oldest. */
10
+ export const MAX_RATE_KEYS = 200;
11
+ /** Returns false once `max` events have happened inside `windowMs`, and prunes as
12
+ * it goes so the map cannot grow forever. */
13
+ export function withinRate(seen, key, now, max, windowMs) {
14
+ const cutoff = now - windowMs;
15
+ const hits = (seen.get(key) ?? []).filter((t) => t > cutoff);
16
+ if (hits.length >= max) {
17
+ seen.set(key, hits);
18
+ return false;
19
+ }
20
+ hits.push(now);
21
+ seen.set(key, hits);
22
+ // A busy workspace must not accumulate a key per thread forever.
23
+ if (seen.size > MAX_RATE_KEYS) {
24
+ const oldest = seen.keys().next().value;
25
+ if (oldest !== undefined && oldest !== key)
26
+ seen.delete(oldest);
27
+ }
28
+ return true;
29
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Splitting a message Rocket.Chat would refuse.
3
+ *
4
+ * Rocket.Chat enforces `Message_MaxAllowedSize` (5000 characters by default) and
5
+ * answers a longer `chat.postMessage` or `chat.sendMessage` with 400
6
+ * `error-message-size-exceeded`. Nothing of the message is posted. So a long text
7
+ * goes out as several messages instead of vanishing.
8
+ */
9
+ /** Ceiling per message, under Rocket.Chat's default 5000 so a part plus its
10
+ * continuation marker and a closing fence still fits. */
11
+ export declare const RC_MAX_MESSAGE_CHARS = 4000;
12
+ /** How many parts one text may become. A runaway text turns into a readable
13
+ * prefix plus a truncation notice, never fifty messages. */
14
+ export declare const RC_MAX_PARTS = 5;
15
+ /**
16
+ * Split `text` into messages Rocket.Chat will accept.
17
+ *
18
+ * Splits on line boundaries so prose and code stay readable, and tracks ``` fences
19
+ * across a boundary: a part that ends inside a fence closes it, and the next part
20
+ * reopens it. Without that, splitting a log dump renders the rest of the room as
21
+ * one giant code block.
22
+ *
23
+ * Returns `[text]` untouched when it already fits, which is nearly every message.
24
+ */
25
+ export declare function splitForRc(text: string, max?: number, maxParts?: number): string[];
package/dist/split.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Splitting a message Rocket.Chat would refuse.
3
+ *
4
+ * Rocket.Chat enforces `Message_MaxAllowedSize` (5000 characters by default) and
5
+ * answers a longer `chat.postMessage` or `chat.sendMessage` with 400
6
+ * `error-message-size-exceeded`. Nothing of the message is posted. So a long text
7
+ * goes out as several messages instead of vanishing.
8
+ */
9
+ /** Ceiling per message, under Rocket.Chat's default 5000 so a part plus its
10
+ * continuation marker and a closing fence still fits. */
11
+ export const RC_MAX_MESSAGE_CHARS = 4000;
12
+ /** How many parts one text may become. A runaway text turns into a readable
13
+ * prefix plus a truncation notice, never fifty messages. */
14
+ export const RC_MAX_PARTS = 5;
15
+ const CONTINUES = "…";
16
+ const TRUNCATED = "\n\n_[truncated — the rest was too long to post]_";
17
+ /** Is this line a ``` fence? */
18
+ const isFence = (line) => /^\s*```/.test(line);
19
+ /** Hard-split a single oversized line (a pasted blob with no newlines). */
20
+ function splitLongLine(line, max) {
21
+ const out = [];
22
+ for (let i = 0; i < line.length; i += max)
23
+ out.push(line.slice(i, i + max));
24
+ return out;
25
+ }
26
+ /**
27
+ * Split `text` into messages Rocket.Chat will accept.
28
+ *
29
+ * Splits on line boundaries so prose and code stay readable, and tracks ``` fences
30
+ * across a boundary: a part that ends inside a fence closes it, and the next part
31
+ * reopens it. Without that, splitting a log dump renders the rest of the room as
32
+ * one giant code block.
33
+ *
34
+ * Returns `[text]` untouched when it already fits, which is nearly every message.
35
+ */
36
+ export function splitForRc(text, max = RC_MAX_MESSAGE_CHARS, maxParts = RC_MAX_PARTS) {
37
+ if (text.length <= max)
38
+ return [text];
39
+ const parts = [];
40
+ let current = "";
41
+ let fenceOpen = false;
42
+ let currentStartedFenced = false;
43
+ const flush = () => {
44
+ if (!current)
45
+ return;
46
+ // Close a fence this part leaves open, so it renders on its own.
47
+ parts.push(fenceOpen ? `${current}\n\`\`\`` : current);
48
+ current = "";
49
+ currentStartedFenced = fenceOpen;
50
+ };
51
+ const budget = () => max - CONTINUES.length - (currentStartedFenced ? 8 : 0);
52
+ for (const rawLine of text.split("\n")) {
53
+ for (const line of rawLine.length > budget() ? splitLongLine(rawLine, budget()) : [rawLine]) {
54
+ const candidate = current ? `${current}\n${line}` : line;
55
+ if (candidate.length > budget() && current) {
56
+ flush();
57
+ current = currentStartedFenced ? `\`\`\`\n${line}` : line;
58
+ }
59
+ else {
60
+ current = candidate;
61
+ }
62
+ if (isFence(line))
63
+ fenceOpen = !fenceOpen;
64
+ }
65
+ }
66
+ flush();
67
+ if (parts.length <= maxParts)
68
+ return parts;
69
+ // The notice must fit inside the ceiling too, so the last kept part gives up
70
+ // room for it, keeping a closing fence it carries.
71
+ const kept = parts.slice(0, maxParts);
72
+ const last = kept[kept.length - 1] ?? "";
73
+ const fence = last.endsWith("\n```") ? "\n```" : "";
74
+ const room = max - TRUNCATED.length - fence.length;
75
+ const body = fence ? last.slice(0, -fence.length) : last;
76
+ kept[kept.length - 1] = `${body.slice(0, room)}${fence}${TRUNCATED}`;
77
+ return kept;
78
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Normalize a post target, preserving the sigil that decides WHERE it lands:
3
+ * `#name` is a channel, `@name` is a direct message. A bare name is a channel,
4
+ * since that is the common case and the safer default (a channel post is visible
5
+ * and correctable; a DM to the wrong person is not).
6
+ *
7
+ * Case-folded so "#General" and "general" are one target, and so an allowlist
8
+ * entry cannot be bypassed by capitalization.
9
+ */
10
+ export declare function normalizeChannel(target: string): string;
11
+ /** Is this target a direct message rather than a channel post? */
12
+ export declare function isDirectTarget(target: string): boolean;
13
+ /**
14
+ * Normalize a list of post targets into the set an allowlist check compares
15
+ * against. Entries may be channels (`general`, `#general`) or DMs (`@sam`).
16
+ *
17
+ * An empty list yields an EMPTY set, which callers must treat as "posting is
18
+ * off" rather than "everything is allowed": the caller is often an unattended
19
+ * scheduled job, and the failure that matters is a stray post landing in front
20
+ * of the wrong audience.
21
+ */
22
+ export declare function normalizeTargets(targets: readonly string[]): Set<string>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Normalize a post target, preserving the sigil that decides WHERE it lands:
3
+ * `#name` is a channel, `@name` is a direct message. A bare name is a channel,
4
+ * since that is the common case and the safer default (a channel post is visible
5
+ * and correctable; a DM to the wrong person is not).
6
+ *
7
+ * Case-folded so "#General" and "general" are one target, and so an allowlist
8
+ * entry cannot be bypassed by capitalization.
9
+ */
10
+ export function normalizeChannel(target) {
11
+ const trimmed = target.trim().toLowerCase();
12
+ if (trimmed.startsWith("@"))
13
+ return trimmed;
14
+ return trimmed.replace(/^#/, "");
15
+ }
16
+ /** Is this target a direct message rather than a channel post? */
17
+ export function isDirectTarget(target) {
18
+ return normalizeChannel(target).startsWith("@");
19
+ }
20
+ /**
21
+ * Normalize a list of post targets into the set an allowlist check compares
22
+ * against. Entries may be channels (`general`, `#general`) or DMs (`@sam`).
23
+ *
24
+ * An empty list yields an EMPTY set, which callers must treat as "posting is
25
+ * off" rather than "everything is allowed": the caller is often an unattended
26
+ * scheduled job, and the failure that matters is a stray post landing in front
27
+ * of the wrong audience.
28
+ */
29
+ export function normalizeTargets(targets) {
30
+ return new Set(targets.map(normalizeChannel).filter(Boolean));
31
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@practicalworks/rc-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A typed Rocket.Chat REST client: posts by name, room or thread, replies with a fallback, reactions, room type, uploads, auth status, and splitting a message Rocket.Chat would refuse.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "keywords": [
19
+ "rocket.chat",
20
+ "rocketchat",
21
+ "chat",
22
+ "client"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "test": "vitest run"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^22.0.0",
34
+ "typescript": "^5.5.0",
35
+ "vitest": "^3.0.0"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/PracticalWorks/rc-bridge.git",
40
+ "directory": "packages/client"
41
+ },
42
+ "publishConfig": {
43
+ "registry": "https://registry.npmjs.org/",
44
+ "access": "public",
45
+ "provenance": true
46
+ }
47
+ }